|
1 | 1 | """Configuration for Pydantic models."""
|
2 | 2 | from __future__ import annotations as _annotations
|
3 | 3 |
|
4 |
| -from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, Union |
| 4 | +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Type, TypeVar, Union |
5 | 5 |
|
6 | 6 | from typing_extensions import Literal, TypeAlias, TypedDict
|
7 | 7 |
|
|
11 | 11 | if TYPE_CHECKING:
|
12 | 12 | from ._internal._generate_schema import GenerateSchema as _GenerateSchema
|
13 | 13 |
|
14 |
| -__all__ = ('ConfigDict',) |
| 14 | +__all__ = ('ConfigDict', 'with_config') |
15 | 15 |
|
16 | 16 |
|
17 | 17 | JsonValue: TypeAlias = Union[int, float, str, bool, None, List['JsonValue'], 'JsonDict']
|
@@ -945,4 +945,40 @@ class Model(BaseModel):
|
945 | 945 | '''
|
946 | 946 |
|
947 | 947 |
|
| 948 | +_TypeT = TypeVar('_TypeT', bound=type) |
| 949 | + |
| 950 | + |
| 951 | +def with_config(config: ConfigDict) -> Callable[[_TypeT], _TypeT]: |
| 952 | + """Usage docs: https://docs.pydantic.dev/2.6/concepts/config/#configuration-with-dataclass-from-the-standard-library-or-typeddict |
| 953 | +
|
| 954 | + A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library. |
| 955 | +
|
| 956 | + Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers, |
| 957 | + especially with `TypedDict`. |
| 958 | +
|
| 959 | + !!! example "Usage" |
| 960 | +
|
| 961 | + ```py |
| 962 | + from typing_extensions import TypedDict |
| 963 | +
|
| 964 | + from pydantic import ConfigDict, TypeAdapter, with_config |
| 965 | +
|
| 966 | + @with_config(ConfigDict(str_to_lower=True)) |
| 967 | + class Model(TypedDict): |
| 968 | + x: str |
| 969 | +
|
| 970 | + ta = TypeAdapter(Model) |
| 971 | +
|
| 972 | + print(ta.validate_python({'x': 'ABC'})) |
| 973 | + #> {'x': 'abc'} |
| 974 | + ``` |
| 975 | + """ |
| 976 | + |
| 977 | + def inner(TypedDictClass: _TypeT, /) -> _TypeT: |
| 978 | + TypedDictClass.__pydantic_config__ = config |
| 979 | + return TypedDictClass |
| 980 | + |
| 981 | + return inner |
| 982 | + |
| 983 | + |
948 | 984 | __getattr__ = getattr_migration(__name__)
|
0 commit comments