Coverage for pydantic / _internal / _dataclasses.py: 98.40%
97 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1"""Private logic for creating pydantic dataclasses."""
3from __future__ import annotations as _annotations 1jklabcmnodefspqrghi
5import copy 1jklabcmnodefspqrghi
6import dataclasses 1jklabcmnodefspqrghi
7import sys 1jklabcmnodefspqrghi
8from collections.abc import Generator 1jklabcmnodefspqrghi
9from functools import partial 1jklabcmnodefspqrghi
10from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeAlias, cast 1jklabcmnodefspqrghi
12from pydantic_core import ( 1jklabcmnodefspqrghi
13 ArgsKwargs,
14 SchemaSerializer,
15 SchemaValidator,
16 core_schema,
17)
18from typing_extensions import TypeIs 1jklabcmnodefspqrghi
20from ..errors import PydanticUndefinedAnnotation 1jklabcmnodefspqrghi
21from ..fields import FieldInfo 1jklabcmnodefspqrghi
22from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator 1jklabcmnodefspqrghi
23from . import _config, _decorators 1jklabcmnodefspqrghi
24from ._contextlib import contextmanager 1jklabcmnodefspqrghi
25from ._fields import collect_dataclass_fields 1jklabcmnodefspqrghi
26from ._generate_schema import GenerateSchema, InvalidSchemaError 1jklabcmnodefspqrghi
27from ._generics import get_standard_typevars_map 1jklabcmnodefspqrghi
28from ._mock_val_ser import set_dataclass_mocks 1jklabcmnodefspqrghi
29from ._namespace_utils import NsResolver 1jklabcmnodefspqrghi
30from ._signature import generate_pydantic_signature 1jklabcmnodefspqrghi
31from ._utils import LazyClassAttribute 1jklabcmnodefspqrghi
33if TYPE_CHECKING: 1jklabcmnodefspqrghi
34 from _typeshed import DataclassInstance as StandardDataclass
36 from ..config import ConfigDict
38 class PydanticDataclass(StandardDataclass, Protocol):
39 """A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass.
41 Attributes:
42 __pydantic_config__: Pydantic-specific configuration settings for the dataclass.
43 __pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields.
44 __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
45 __pydantic_decorators__: Metadata containing the decorators defined on the dataclass.
46 __pydantic_fields__: Metadata about the fields defined on the dataclass.
47 __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass.
48 __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass.
49 """
51 __pydantic_config__: ClassVar[ConfigDict]
52 __pydantic_complete__: ClassVar[bool]
53 __pydantic_core_schema__: ClassVar[core_schema.CoreSchema]
54 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos]
55 __pydantic_fields__: ClassVar[dict[str, FieldInfo]]
56 __pydantic_serializer__: ClassVar[SchemaSerializer]
57 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
59 @classmethod
60 def __pydantic_fields_complete__(cls) -> bool: ...
63def set_dataclass_fields( 1jklabcmnodefspqrghi
64 cls: type[StandardDataclass],
65 config_wrapper: _config.ConfigWrapper,
66 ns_resolver: NsResolver | None = None,
67) -> None:
68 """Collect and set `cls.__pydantic_fields__`.
70 Args:
71 cls: The class.
72 config_wrapper: The config wrapper instance.
73 ns_resolver: Namespace resolver to use when getting dataclass annotations.
74 """
75 typevars_map = get_standard_typevars_map(cls) 1jklabcmnodefspqrghi
76 fields = collect_dataclass_fields( 1jklabcmnodefspqrghi
77 cls, ns_resolver=ns_resolver, typevars_map=typevars_map, config_wrapper=config_wrapper
78 )
80 cls.__pydantic_fields__ = fields # type: ignore 1jklabcmnodefspqrghi
83def complete_dataclass( 1jklabcmnodefspqrghi
84 cls: type[Any],
85 config_wrapper: _config.ConfigWrapper,
86 *,
87 raise_errors: bool = True,
88 ns_resolver: NsResolver | None = None,
89 _force_build: bool = False,
90) -> bool:
91 """Finish building a pydantic dataclass.
93 This logic is called on a class which has already been wrapped in `dataclasses.dataclass()`.
95 This is somewhat analogous to `pydantic._internal._model_construction.complete_model_class`.
97 Args:
98 cls: The class.
99 config_wrapper: The config wrapper instance.
100 raise_errors: Whether to raise errors, defaults to `True`.
101 ns_resolver: The namespace resolver instance to use when collecting dataclass fields
102 and during schema building.
103 _force_build: Whether to force building the dataclass, no matter if
104 [`defer_build`][pydantic.config.ConfigDict.defer_build] is set.
106 Returns:
107 `True` if building a pydantic dataclass is successfully completed, `False` otherwise.
109 Raises:
110 PydanticUndefinedAnnotation: If `raise_error` is `True` and there is an undefined annotations.
111 """
112 original_init = cls.__init__ 1jklabcmnodefspqrghi
114 # dataclass.__init__ must be defined here so its `__qualname__` can be changed since functions can't be copied,
115 # and so that the mock validator is used if building was deferred:
116 def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -> None: 1jklabcmnodefspqrghi
117 __tracebackhide__ = True 1jklabcmnodefspqrghi
118 s = __dataclass_self__ 1jklabcmnodefspqrghi
119 s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s) 1jklabcmnodefspqrghi
121 __init__.__qualname__ = f'{cls.__qualname__}.__init__' 1jklabcmnodefspqrghi
123 cls.__init__ = __init__ # type: ignore 1jklabcmnodefspqrghi
124 cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore 1jklabcmnodefspqrghi
126 set_dataclass_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver) 1jklabcmnodefspqrghi
128 if not _force_build and config_wrapper.defer_build: 1jklabcmnodefspqrghi
129 set_dataclass_mocks(cls) 1jklabcmnodefpqrghi
130 return False 1jklabcmnodefpqrghi
132 typevars_map = get_standard_typevars_map(cls) 1jklabcmnodefspqrghi
133 gen_schema = GenerateSchema( 1jklabcmnodefspqrghi
134 config_wrapper,
135 ns_resolver=ns_resolver,
136 typevars_map=typevars_map,
137 )
139 # set __signature__ attr only for the class, but not for its instances
140 # (because instances can define `__call__`, and `inspect.signature` shouldn't
141 # use the `__signature__` attribute and instead generate from `__call__`).
142 cls.__signature__ = LazyClassAttribute( 1jklabcmnodefspqrghi
143 '__signature__',
144 partial(
145 generate_pydantic_signature,
146 # It's important that we reference the `original_init` here,
147 # as it is the one synthesized by the stdlib `dataclass` module:
148 init=original_init,
149 fields=cls.__pydantic_fields__, # type: ignore
150 validate_by_alias=config_wrapper.validate_by_alias,
151 extra=config_wrapper.extra,
152 is_dataclass=True,
153 ),
154 )
156 try: 1jklabcmnodefspqrghi
157 schema = gen_schema.generate_schema(cls) 1jklabcmnodefspqrghi
158 except PydanticUndefinedAnnotation as e: 1jklabcmnodefpqrghi
159 if raise_errors: 1jklabcmnodefpqrghi
160 raise 1jklabcmnodefpqrghi
161 set_dataclass_mocks(cls, f'`{e.name}`' if e.name is not None else None) 1jklabcmnodefpqrghi
162 return False 1jklabcmnodefpqrghi
164 core_config = config_wrapper.core_config(title=cls.__name__) 1jklabcmnodefspqrghi
166 try: 1jklabcmnodefspqrghi
167 schema = gen_schema.clean_schema(schema) 1jklabcmnodefspqrghi
168 except InvalidSchemaError: 1abcdefghi
169 set_dataclass_mocks(cls)
170 return False
172 # We are about to set all the remaining required properties expected for this cast;
173 # __pydantic_decorators__ and __pydantic_fields__ should already be set
174 cls = cast('type[PydanticDataclass]', cls) 1jklabcmnodefspqrghi
176 cls.__pydantic_core_schema__ = schema 1jklabcmnodefspqrghi
177 cls.__pydantic_validator__ = create_schema_validator( 1jklabcmnodefspqrghi
178 schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings
179 )
180 cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config) 1jklabcmnodefspqrghi
181 cls.__pydantic_complete__ = True 1jklabcmnodefspqrghi
182 return True 1jklabcmnodefspqrghi
185def is_stdlib_dataclass(cls: type[Any], /) -> TypeIs[type[StandardDataclass]]: 1jklabcmnodefspqrghi
186 """Returns `True` if the class is a stdlib dataclass and *not* a Pydantic dataclass.
188 Unlike the stdlib `dataclasses.is_dataclass()` function, this does *not* include subclasses
189 of a dataclass that are themselves not dataclasses.
191 Args:
192 cls: The class.
194 Returns:
195 `True` if the class is a stdlib dataclass, `False` otherwise.
196 """
197 return '__dataclass_fields__' in cls.__dict__ and not hasattr(cls, '__pydantic_validator__') 1jklabcmnodefspqrghi
200def as_dataclass_field(pydantic_field: FieldInfo) -> dataclasses.Field[Any]: 1jklabcmnodefspqrghi
201 field_args: dict[str, Any] = {'default': pydantic_field} 1jklabcmnodefpqrghi
203 # Needed because if `doc` is set, the dataclass slots will be a dict (field name -> doc) instead of a tuple:
204 if sys.version_info >= (3, 14) and pydantic_field.description is not None: 1jklabcmnodefpqrghi
205 field_args['doc'] = pydantic_field.description 1abcdefghi
207 # Needed as the stdlib dataclass module processes `kw_only` in a specific way during class construction:
208 if pydantic_field.kw_only is not None: 1jklabcmnodefpqrghi
209 field_args['kw_only'] = pydantic_field.kw_only 1jklabcmnodefpqrghi
211 # Needed as the stdlib dataclass modules generates `__repr__()` during class construction:
212 if pydantic_field.repr is not True: 1jklabcmnodefpqrghi
213 field_args['repr'] = pydantic_field.repr 1jklabcmnodefpqrghi
215 # Needed as the stdlib dataclass module uses `init` during class construction (e.g. to generate `__match_args__`),
216 # and `dataclasses.replace()` relies on it:
217 if pydantic_field.init is False: 1jklabcmnodefpqrghi
218 field_args['init'] = False 1jklabcmnodefpqrghi
220 return dataclasses.field(**field_args) 1jklabcmnodefpqrghi
223DcFields: TypeAlias = dict[str, dataclasses.Field[Any]] 1jklabcmnodefspqrghi
226@contextmanager 1jklabcmnodefspqrghi
227def patch_base_fields(cls: type[Any]) -> Generator[None]: 1jklabcmnodefspqrghi
228 """Temporarily patch the stdlib dataclasses bases of `cls` if the Pydantic `Field()` function is used.
230 When creating a Pydantic dataclass, it is possible to inherit from stdlib dataclasses, where
231 the Pydantic `Field()` function is used. To create this Pydantic dataclass, we first apply
232 the stdlib `@dataclass` decorator on it. During the construction of the stdlib dataclass,
233 the `kw_only`, `repr` and `init` field arguments need to be understood by the stdlib *during* the
234 dataclass construction. To do so, we temporarily patch the fields dictionary of the affected
235 bases.
237 For instance, with the following example:
239 ```python {test="skip" lint="skip"}
240 import dataclasses as stdlib_dc
242 import pydantic
243 import pydantic.dataclasses as pydantic_dc
245 @stdlib_dc.dataclass
246 class A:
247 a: int = pydantic.Field(repr=False)
249 # Notice that the `repr` attribute of the dataclass field is `True`:
250 A.__dataclass_fields__['a']
251 #> dataclass.Field(default=FieldInfo(repr=False), repr=True, ...)
253 @pydantic_dc.dataclass
254 class B(A):
255 b: int = pydantic.Field(repr=False)
256 ```
258 When passing `B` to the stdlib `@dataclass` decorator, it will look for fields in the parent classes
259 and reuse them directly. When this context manager is active, `A` will be temporarily patched to be
260 equivalent to:
262 ```python {test="skip" lint="skip"}
263 @stdlib_dc.dataclass
264 class A:
265 a: int = stdlib_dc.field(default=Field(repr=False), repr=False)
266 ```
268 !!! note
269 This is only applied to the bases of `cls`, and not `cls` itself. The reason is that the Pydantic
270 dataclass decorator "owns" `cls` (in the previous example, `B`). As such, we instead modify the fields
271 directly (in the previous example, we simply do `setattr(B, 'b', as_dataclass_field(pydantic_field))`).
273 !!! note
274 This approach is far from ideal, and can probably be the source of unwanted side effects/race conditions.
275 The previous implemented approach was mutating the `__annotations__` dict of `cls`, which is no longer a
276 safe operation in Python 3.14+, and resulted in unexpected behavior with field ordering anyway.
277 """
278 # A list of two-tuples, the first element being a reference to the
279 # dataclass fields dictionary, the second element being a mapping between
280 # the field names that were modified, and their original `Field`:
281 original_fields_list: list[tuple[DcFields, DcFields]] = [] 1jklabcmnodefspqrghi
283 for base in cls.__mro__[1:]: 1jklabcmnodefspqrghi
284 dc_fields: dict[str, dataclasses.Field[Any]] = base.__dict__.get('__dataclass_fields__', {}) 1jklabcmnodefspqrghi
285 dc_fields_with_pydantic_field_defaults = { 1jklabcmnodefspqrghi
286 field_name: field
287 for field_name, field in dc_fields.items()
288 if isinstance(field.default, FieldInfo)
289 # Only do the patching if one of the affected attributes is set:
290 and (
291 field.default.description is not None
292 or field.default.kw_only is not None
293 or field.default.repr is not True
294 or field.default.init is False
295 )
296 }
297 if dc_fields_with_pydantic_field_defaults: 1jklabcmnodefspqrghi
298 original_fields_list.append((dc_fields, dc_fields_with_pydantic_field_defaults)) 1jklabcmnodefpqrghi
299 for field_name, field in dc_fields_with_pydantic_field_defaults.items(): 1jklabcmnodefpqrghi
300 default = cast(FieldInfo, field.default) 1jklabcmnodefpqrghi
301 # `dataclasses.Field` isn't documented as working with `copy.copy()`.
302 # It is a class with `__slots__`, so should work (and we hope for the best):
303 new_dc_field = copy.copy(field) 1jklabcmnodefpqrghi
304 # For base fields, no need to set `doc` from `FieldInfo.description`, this is only relevant
305 # for the class under construction and handled in `as_dataclass_field()`.
306 if default.kw_only is not None: 1jklabcmnodefpqrghi
307 new_dc_field.kw_only = default.kw_only 1jklabcmnodefpqrghi
308 if default.repr is not True: 1jklabcmnodefpqrghi
309 new_dc_field.repr = default.repr 1jklabcmnodefpqrghi
310 if default.init is False: 1jklabcmnodefpqrghi
311 new_dc_field.init = False 1jklabcmnodefpqrghi
312 dc_fields[field_name] = new_dc_field 1jklabcmnodefpqrghi
314 try: 1jklabcmnodefspqrghi
315 yield 1jklabcmnodefspqrghi
316 finally:
317 for fields, original_fields in original_fields_list: 1jklabcmnodefspqrghi
318 for field_name, original_field in original_fields.items(): 1jklabcmnodefpqrghi
319 fields[field_name] = original_field 1jklabcmnodefpqrghi