Coverage for pydantic / dataclasses.py: 97.28%
107 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"""Provide an enhanced dataclass that performs validation."""
3from __future__ import annotations as _annotations 1pdaghiqebjklsrfcmno
5import dataclasses 1pdaghiqebjklsrfcmno
6import functools 1pdaghiqebjklsrfcmno
7import sys 1pdaghiqebjklsrfcmno
8import types 1pdaghiqebjklsrfcmno
9from collections.abc import Callable 1pdaghiqebjklsrfcmno
10from typing import TYPE_CHECKING, Any, Generic, Literal, TypeGuard, TypeVar, dataclass_transform, overload 1pdaghiqebjklsrfcmno
11from warnings import warn 1pdaghiqebjklsrfcmno
13from ._internal import _config, _decorators, _mock_val_ser, _namespace_utils, _typing_extra 1pdaghiqebjklsrfcmno
14from ._internal import _dataclasses as _pydantic_dataclasses 1pdaghiqebjklsrfcmno
15from .config import ConfigDict 1pdaghiqebjklsrfcmno
16from .errors import PydanticUserError 1pdaghiqebjklsrfcmno
17from .fields import Field, FieldInfo, PrivateAttr 1pdaghiqebjklsrfcmno
19if TYPE_CHECKING: 1pdaghiqebjklsrfcmno
20 from ._internal._dataclasses import PydanticDataclass
21 from ._internal._namespace_utils import MappingNamespace
23__all__ = 'dataclass', 'rebuild_dataclass' 1pdaghiqebjklsrfcmno
25_T = TypeVar('_T') 1pdaghiqebjklsrfcmno
28@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1pdaghiqebjklsrfcmno
29@overload 1pdaghiqebjklsrfcmno
30def dataclass( 1pdaghiqebjklsrfcmno
31 *,
32 init: Literal[False] = False, 1pdaghiqebjklsrfcmno
33 repr: bool = True, 1pdaghiqebjklsrfcmno
34 eq: bool = True, 1pdaghiqebjklsrfcmno
35 order: bool = False, 1pdaghiqebjklsrfcmno
36 unsafe_hash: bool = False, 1pdaghiqebjklsrfcmno
37 frozen: bool = False, 1pdaghiqebjklsrfcmno
38 config: ConfigDict | None = None, 1pdaghiqebjklsrfcmno
39 kw_only: bool = ..., 1pdaghiqebjklsrfcmno
40 slots: bool = ..., 1pdaghiqebjklsrfcmno
41) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore 1daebsfc
42 ...
45@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1pdaghiqebjklsrfcmno
46@overload 1pdaghiqebjklsrfcmno
47def dataclass( 1pdaghiqebjklsrfcmno
48 _cls: type[_T], # type: ignore 1daebsfc
49 *,
50 init: Literal[False] = False, 1pdaghiqebjklsrfcmno
51 repr: bool = True, 1pdaghiqebjklsrfcmno
52 eq: bool = True, 1pdaghiqebjklsrfcmno
53 order: bool = False, 1pdaghiqebjklsrfcmno
54 unsafe_hash: bool = False, 1pdaghiqebjklsrfcmno
55 frozen: bool | None = None, 1pdaghiqebjklsrfcmno
56 config: ConfigDict | None = None, 1pdaghiqebjklsrfcmno
57 kw_only: bool = ..., 1pdaghiqebjklsrfcmno
58 slots: bool = ..., 1pdaghiqebjklsrfcmno
59) -> type[PydanticDataclass]: ... 1daebsfc
60@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1pdaghiqebjklsrfcmno
61def dataclass( 1pdaghiqebjklsrfcmno
62 _cls: type[_T] | None = None,
63 *,
64 init: Literal[False] = False,
65 repr: bool = True,
66 eq: bool = True,
67 order: bool = False,
68 unsafe_hash: bool = False,
69 frozen: bool | None = None,
70 config: ConfigDict | None = None,
71 kw_only: bool = False,
72 slots: bool = False,
73) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
74 """!!! abstract "Usage Documentation"
75 [`dataclasses`](../concepts/dataclasses.md)
77 A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
78 but with added validation.
80 This decorator should be used similarly to the [`@dataclasses.dataclass`][dataclasses.dataclass] decorator.
82 A Pydantic dataclass validates its inputs like a `BaseModel` does. Its
83 [`ValidationError`][pydantic_core.ValidationError] includes each rejected value, while
84 [Logfire](../integrations/logfire.md) can retain the complete validation input and surrounding trace
85 context — see [Troubleshooting validation errors](../errors/troubleshooting.md).
87 Args:
88 _cls: The target `dataclass`.
89 init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
90 `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
91 own `__init__()` function.
92 repr: A boolean indicating whether to include the field in the `__repr__()` output.
93 eq: Determines if a `__eq__()` method should be generated for the class.
94 order: Determines if comparison magic methods should be generated, such as `__lt__()`, but not `__eq__()`.
95 unsafe_hash: Determines if a `__hash__()` method should be included in the class, as in `dataclasses.dataclass`.
96 frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
97 attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise).
98 config: The Pydantic config to use for the `dataclass`.
99 kw_only: Determines if `__init__()` method parameters must be specified by keyword only. Defaults to `False`.
100 slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
101 new attributes after instantiation.
103 Returns:
104 A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
106 Raises:
107 AssertionError: Raised if `init` is not `False`.
108 """
109 assert init is False, 'pydantic.dataclasses.dataclass only supports init=False' 1pdaghiqebjklsrfcmno
111 def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]: 1pdaghiqebjklsrfcmno
112 """Create a Pydantic dataclass from a regular dataclass.
114 Args:
115 cls: The class to create the Pydantic dataclass from.
117 Returns:
118 A Pydantic dataclass.
119 """
120 from ._internal._utils import is_model_class 1pdaghiqebjklsrfcmno
122 if is_model_class(cls): 1pdaghiqebjklsrfcmno
123 raise PydanticUserError( 1pdaghiqebjklrfcmno
124 f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
125 code='dataclass-on-model',
126 )
128 original_cls = cls 1pdaghiqebjklsrfcmno
130 # we warn on conflicting config specifications, but only if the class doesn't have a dataclass base
131 # because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about
132 has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__) 1pdaghiqebjklsrfcmno
133 if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'): 1pdaghiqebjklsrfcmno
134 warn( 1pdaghiqebjklrfcmno
135 f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. '
136 f'The `config` specification from `dataclass` decorator will take priority.',
137 category=UserWarning,
138 stacklevel=2,
139 )
141 # if config is not explicitly provided, try to read it from the type
142 config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None) 1pdaghiqebjklsrfcmno
143 config_wrapper = _config.ConfigWrapper(config_dict) 1pdaghiqebjklsrfcmno
144 decorators = _decorators.DecoratorInfos.build(cls, replace_wrapped_methods=True) 1pdaghiqebjklsrfcmno
145 decorators.update_from_config(config_wrapper) 1pdaghiqebjklsrfcmno
147 # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
148 # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
149 # since dataclasses.dataclass will set this as the __doc__
150 original_doc = cls.__doc__ 1pdaghiqebjklsrfcmno
152 if _pydantic_dataclasses.is_stdlib_dataclass(cls): 1pdaghiqebjklsrfcmno
153 # Vanilla dataclasses include a default docstring (representing the class signature),
154 # which we don't want to preserve.
155 original_doc = None 1pdaghiqebjklrfcmno
157 # We don't want to add validation to the existing std lib dataclass, so we will subclass it
158 # If the class is generic, we need to make sure the subclass also inherits from Generic
159 # with all the same parameters.
160 bases = (cls,) 1pdaghiqebjklrfcmno
161 if issubclass(cls, Generic): 1pdaghiqebjklrfcmno
162 generic_base = Generic[cls.__parameters__] # type: ignore 1pdaghiqebjklrfcmno
163 bases = bases + (generic_base,) 1pdaghiqebjklrfcmno
164 cls = types.new_class(cls.__name__, bases) 1pdaghiqebjklrfcmno
166 # Respect frozen setting from dataclass constructor and fallback to config setting if not provided
167 if frozen is not None: 1pdaghiqebjklsrfcmno
168 frozen_ = frozen 1pdaghiqebjklrfcmno
169 if config_wrapper.frozen: 1pdaghiqebjklrfcmno
170 # It's not recommended to define both, as the setting from the dataclass decorator will take priority.
171 warn( 1pdaghiqebjklrfcmno
172 f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.'
173 'This is not recommended. The `frozen` specification on `dataclass` will take priority.',
174 category=UserWarning,
175 stacklevel=2,
176 )
177 else:
178 frozen_ = config_wrapper.frozen or False 1pdaghiqebjklsrfcmno
180 # Make Pydantic's `Field()` function compatible with stdlib dataclasses. As we'll decorate
181 # `cls` with the stdlib `@dataclass` decorator first, some attributes (`kw_only`, `repr`, `init`)
182 # need to be understood *during* the stdlib creation. We do so in two steps:
184 # 1. On the decorated class, wrap `Field()` assignment with `dataclass.field()`, with these
185 # attributes set (done in `as_dataclass_field()`)
186 cls_anns = _typing_extra.safe_get_annotations(cls) 1pdaghiqebjklsrfcmno
187 for field_name in cls_anns: 1pdaghiqebjklsrfcmno
188 # We should look for assignments in `__dict__` instead, but for now we follow
189 # the same behavior as stdlib dataclasses (see https://github.com/python/cpython/issues/88609)
190 field_value = getattr(cls, field_name, None) 1pdaghiqebjklsrfcmno
191 if isinstance(field_value, FieldInfo): 1pdaghiqebjklsrfcmno
192 setattr(cls, field_name, _pydantic_dataclasses.as_dataclass_field(field_value)) 1pdaghiqebjklrfcmno
194 # 2. For bases of `cls` that are stdlib dataclasses, we temporarily patch their fields
195 # (see the docstring of the context manager):
196 with _pydantic_dataclasses.patch_base_fields(cls): 1pdaghiqebjklsrfcmno
197 cls = dataclasses.dataclass( # pyright: ignore[reportCallIssue] 1pdaghiqebjklsrfcmno
198 cls,
199 # the value of init here doesn't affect anything except that it makes it easier to generate a signature
200 init=True,
201 repr=repr,
202 eq=eq,
203 order=order,
204 unsafe_hash=unsafe_hash,
205 frozen=frozen_,
206 kw_only=kw_only,
207 slots=slots,
208 )
210 if config_wrapper.validate_assignment: 1pdaghiqebjklsrfcmno
211 original_setattr = cls.__setattr__ 1pdaghiqebjklsrfcmno
213 @functools.wraps(cls.__setattr__) 1pdaghiqebjklsrfcmno
214 def validated_setattr(instance: PydanticDataclass, name: str, value: Any, /) -> None: 1pdaghiqebjklsrfcmno
215 if frozen_: 1pdaghiqebjklrfcmno
216 return original_setattr(instance, name, value) # pyright: ignore[reportCallIssue] 1pdaghiqebjklrfcmno
217 inst_cls = type(instance) 1pdaghiqebjklrfcmno
218 attr = getattr(inst_cls, name, None) 1pdaghiqebjklrfcmno
220 if isinstance(attr, property): 1pdaghiqebjklrfcmno
221 attr.__set__(instance, value) 1pdaghiqebjklrfcmno
222 elif isinstance(attr, functools.cached_property): 1pdaghiqebjklrfcmno
223 instance.__dict__.__setitem__(name, value) 1pdaghiqebjklrfcmno
224 else:
225 inst_cls.__pydantic_validator__.validate_assignment(instance, name, value) 1pdaghiqebjklrfcmno
227 cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore 1pdaghiqebjklsrfcmno
229 if slots and not hasattr(cls, '__setstate__'): 1pdaghiqebjklsrfcmno
230 # If slots is set, `pickle` (relied on by `copy.copy()`) will use
231 # `__setattr__()` to reconstruct the dataclass. However, the custom
232 # `__setattr__()` set above relies on `validate_assignment()`, which
233 # in turn expects all the field values to be already present on the
234 # instance, resulting in attribute errors.
235 # As such, we make use of `object.__setattr__()` instead.
236 # Note that we do so only if `__setstate__()` isn't already set (this is the
237 # case if on top of `slots`, `frozen` is used).
239 # Taken from `dataclasses._dataclass_get/setstate()`:
240 def _dataclass_getstate(self: Any) -> list[Any]: 1pdaghiqebjklrfcmno
241 return [getattr(self, f.name) for f in dataclasses.fields(self)] 1pdaghiqebjklrfcmno
243 def _dataclass_setstate(self: Any, state: list[Any]) -> None: 1pdaghiqebjklrfcmno
244 for field, value in zip(dataclasses.fields(self), state, strict=True): 1pdaghiqebjklrfcmno
245 object.__setattr__(self, field.name, value) 1pdaghiqebjklrfcmno
247 cls.__getstate__ = _dataclass_getstate # pyright: ignore[reportAttributeAccessIssue] 1pdaghiqebjklrfcmno
248 cls.__setstate__ = _dataclass_setstate # pyright: ignore[reportAttributeAccessIssue] 1pdaghiqebjklrfcmno
250 # This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses.
251 # It should be set as early as possible:
252 cls.__is_pydantic_dataclass__ = True 1pdaghiqebjklsrfcmno
253 cls.__pydantic_decorators__ = decorators # type: ignore 1pdaghiqebjklsrfcmno
254 cls.__doc__ = original_doc 1pdaghiqebjklsrfcmno
255 # Can be non-existent for dynamically created classes:
256 firstlineno = getattr(original_cls, '__firstlineno__', None) 1pdaghiqebjklsrfcmno
257 cls.__module__ = original_cls.__module__ 1pdaghiqebjklsrfcmno
258 if sys.version_info >= (3, 13) and firstlineno is not None: 1pdaghiqebjklsrfcmno
259 # As per https://docs.python.org/3/reference/datamodel.html#type.__firstlineno__:
260 # Setting the `__module__` attribute removes the `__firstlineno__` item from the type’s dictionary.
261 original_cls.__firstlineno__ = firstlineno 1aghibjklscmno
262 cls.__firstlineno__ = firstlineno 1aghibjklscmno
263 cls.__qualname__ = original_cls.__qualname__ 1pdaghiqebjklsrfcmno
264 cls.__pydantic_fields_complete__ = classmethod(_pydantic_fields_complete) 1pdaghiqebjklsrfcmno
265 cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful. 1pdaghiqebjklsrfcmno
266 # TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models:
267 # fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function),
268 # and possibly cache it (see the `__pydantic_parent_namespace__` logic for models).
269 _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False) 1pdaghiqebjklsrfcmno
270 return cls 1pdaghiqebjklsrfcmno
272 return create_dataclass if _cls is None else create_dataclass(_cls) 1pdaghiqebjklsrfcmno
275def _pydantic_fields_complete(cls: type[PydanticDataclass]) -> bool: 1pdaghiqebjklsrfcmno
276 """Return whether the fields were successfully collected (i.e. type hints were successfully resolved).
278 This is a private helper, not meant to be used outside Pydantic.
279 """
280 return all(field_info._complete for field_info in cls.__pydantic_fields__.values()) 1pdaghiqebjklsrfcmno
283def rebuild_dataclass( 1pdaghiqebjklsrfcmno
284 cls: type[PydanticDataclass],
285 *,
286 force: bool = False,
287 raise_errors: bool = True,
288 _parent_namespace_depth: int = 2,
289 _types_namespace: MappingNamespace | None = None,
290) -> bool | None:
291 """Try to rebuild the pydantic-core schema for the dataclass.
293 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
294 the initial attempt to build the schema, and automatic rebuilding fails.
296 This is analogous to `BaseModel.model_rebuild`.
298 Args:
299 cls: The class to rebuild the pydantic-core schema for.
300 force: Whether to force the rebuilding of the schema, defaults to `False`.
301 raise_errors: Whether to raise errors, defaults to `True`.
302 _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
303 _types_namespace: The types namespace, defaults to `None`.
305 Returns:
306 Returns `None` if the schema is already "complete" and rebuilding was not required.
307 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
308 """
309 if not force and cls.__pydantic_complete__: 1pdaghiqebjklrfcmno
310 return None 1pdaghiqebjklrfcmno
312 for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): 1pdaghiqebjklrfcmno
313 if attr in cls.__dict__ and not isinstance( 313 ↛ 320line 313 didn't jump to line 320 because the condition on line 313 was never true1pdaghiqebjklrfcmno
314 getattr(cls, attr), (_mock_val_ser.MockCoreSchema, _mock_val_ser.MockValSer)
315 ):
316 # Deleting the validator/serializer is necessary as otherwise they can get reused in
317 # pydantic-core. Same applies for the core schema that can be reused in schema generation.
318 # We do so only if they aren't mock instances, otherwise concurrent reads of these attributes
319 # (e.g. when instantiating the dataclass in another thread) can resolve them from the parent class.
320 delattr(cls, attr)
322 cls.__pydantic_complete__ = False 1pdaghiqebjklrfcmno
324 if _types_namespace is not None: 1pdaghiqebjklrfcmno
325 rebuild_ns = _types_namespace 1pdaghiqebjklrfcmno
326 elif _parent_namespace_depth > 0: 1pdaghiqebjklrfcmno
327 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 1pdaghiqebjklrfcmno
328 else:
329 rebuild_ns = {} 1pdaghiqebjklrfcmno
331 ns_resolver = _namespace_utils.NsResolver( 1pdaghiqebjklrfcmno
332 parent_namespace=rebuild_ns,
333 )
335 return _pydantic_dataclasses.complete_dataclass( 1pdaghiqebjklrfcmno
336 cls,
337 _config.ConfigWrapper(cls.__pydantic_config__, check=False),
338 raise_errors=raise_errors,
339 ns_resolver=ns_resolver,
340 # We could provide a different config instead (with `'defer_build'` set to `True`)
341 # of this explicit `_force_build` argument, but because config can come from the
342 # decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass`
343 # will overwrite `__pydantic_config__` with the provided config above:
344 _force_build=True,
345 )
348def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]: 1pdaghiqebjklsrfcmno
349 """Whether a class is a pydantic dataclass.
351 Args:
352 class_: The class.
354 Returns:
355 `True` if the class is a pydantic dataclass, `False` otherwise.
356 """
357 try: 1pdaghiqebjklsrfcmno
358 return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_) 1pdaghiqebjklsrfcmno
359 except AttributeError:
360 return False