Coverage for pydantic/dataclasses.py: 98.19%
120 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-07-01 21:48 +0000
« prev ^ index » next coverage.py v7.9.1, created at 2025-07-01 21:48 +0000
1"""Provide an enhanced dataclass that performs validation."""
3from __future__ import annotations as _annotations 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
5import dataclasses 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
6import functools 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
7import sys 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
8import types 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
9from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, NoReturn, TypeVar, overload 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
10from warnings import warn 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
12from typing_extensions import TypeGuard, dataclass_transform 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
14from ._internal import _config, _decorators, _namespace_utils, _typing_extra 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
15from ._internal import _dataclasses as _pydantic_dataclasses 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
16from ._migration import getattr_migration 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
17from .config import ConfigDict 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
18from .errors import PydanticUserError 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
19from .fields import Field, FieldInfo, PrivateAttr 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
21if TYPE_CHECKING: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
22 from ._internal._dataclasses import PydanticDataclass
23 from ._internal._namespace_utils import MappingNamespace
25__all__ = 'dataclass', 'rebuild_dataclass' 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
27_T = TypeVar('_T') 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
29if sys.version_info >= (3, 10): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
31 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1klwxmnabcdopyzqrefgJstABuvhij
32 @overload 1klwxmnabcdopyzqrefgJstABuvhij
33 def dataclass( 1klwxmnabcdopyzqrefgJstABuvhij
34 *,
35 init: Literal[False] = False, 1klwxmnabcdopyzqrefgJstABuvhij
36 repr: bool = True, 1klwxmnabcdopyzqrefgJstABuvhij
37 eq: bool = True, 1klwxmnabcdopyzqrefgJstABuvhij
38 order: bool = False, 1klwxmnabcdopyzqrefgJstABuvhij
39 unsafe_hash: bool = False, 1klwxmnabcdopyzqrefgJstABuvhij
40 frozen: bool = False, 1klwxmnabcdopyzqrefgJstABuvhij
41 config: ConfigDict | type[object] | None = None, 1klwxmnabcdopyzqrefgJstABuvhij
42 validate_on_init: bool | None = None, 1klwxmnabcdopyzqrefgJstABuvhij
43 kw_only: bool = ..., 1klwxmnabcdopyzqrefgJstABuvhij
44 slots: bool = ..., 1klwxmnabcdopyzqrefgJstABuvhij
45 ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore 1mnabcdqrefgJuvhij
46 ...
48 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1klwxmnabcdopyzqrefgJstABuvhij
49 @overload 1klwxmnabcdopyzqrefgJstABuvhij
50 def dataclass( 1klwxmnabcdopyzqrefgJstABuvhij
51 _cls: type[_T], # type: ignore 1mnabcdqrefgJuvhij
52 *,
53 init: Literal[False] = False, 1klwxmnabcdopyzqrefgJstABuvhij
54 repr: bool = True, 1klwxmnabcdopyzqrefgJstABuvhij
55 eq: bool = True, 1klwxmnabcdopyzqrefgJstABuvhij
56 order: bool = False, 1klwxmnabcdopyzqrefgJstABuvhij
57 unsafe_hash: bool = False, 1klwxmnabcdopyzqrefgJstABuvhij
58 frozen: bool | None = None, 1klwxmnabcdopyzqrefgJstABuvhij
59 config: ConfigDict | type[object] | None = None, 1klwxmnabcdopyzqrefgJstABuvhij
60 validate_on_init: bool | None = None, 1klwxmnabcdopyzqrefgJstABuvhij
61 kw_only: bool = ..., 1klwxmnabcdopyzqrefgJstABuvhij
62 slots: bool = ..., 1klwxmnabcdopyzqrefgJstABuvhij
63 ) -> type[PydanticDataclass]: ... 1mnabcdqrefgJuvhij
65else:
67 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1DECFGHI
68 @overload 1DECFGHI
69 def dataclass( 1DECFGHI
70 *,
71 init: Literal[False] = False, 1DECFGHI
72 repr: bool = True, 1DECFGHI
73 eq: bool = True, 1DECFGHI
74 order: bool = False, 1DECFGHI
75 unsafe_hash: bool = False, 1DECFGHI
76 frozen: bool | None = None, 1DECFGHI
77 config: ConfigDict | type[object] | None = None, 1DECFGHI
78 validate_on_init: bool | None = None, 1DECFGHI
79 ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore 1C
80 ...
82 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1DECFGHI
83 @overload 1DECFGHI
84 def dataclass( 1DECFGHI
85 _cls: type[_T], # type: ignore 1C
86 *,
87 init: Literal[False] = False, 1DECFGHI
88 repr: bool = True, 1DECFGHI
89 eq: bool = True, 1DECFGHI
90 order: bool = False, 1DECFGHI
91 unsafe_hash: bool = False, 1DECFGHI
92 frozen: bool | None = None, 1DECFGHI
93 config: ConfigDict | type[object] | None = None, 1DECFGHI
94 validate_on_init: bool | None = None, 1DECFGHI
95 ) -> type[PydanticDataclass]: ... 1C
98@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
99def dataclass( 1DEklwxmnabcFGopyzqrefgJHIstABuvhij
100 _cls: type[_T] | None = None,
101 *,
102 init: Literal[False] = False,
103 repr: bool = True,
104 eq: bool = True,
105 order: bool = False,
106 unsafe_hash: bool = False,
107 frozen: bool | None = None,
108 config: ConfigDict | type[object] | None = None,
109 validate_on_init: bool | None = None,
110 kw_only: bool = False,
111 slots: bool = False,
112) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
113 """!!! abstract "Usage Documentation"
114 [`dataclasses`](../concepts/dataclasses.md)
116 A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
117 but with added validation.
119 This function should be used similarly to `dataclasses.dataclass`.
121 Args:
122 _cls: The target `dataclass`.
123 init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
124 `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
125 own `__init__` function.
126 repr: A boolean indicating whether to include the field in the `__repr__` output.
127 eq: Determines if a `__eq__` method should be generated for the class.
128 order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`.
129 unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`.
130 frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
131 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).
132 config: The Pydantic config to use for the `dataclass`.
133 validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses
134 are validated on init.
135 kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`.
136 slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
137 new attributes after instantiation.
139 Returns:
140 A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
142 Raises:
143 AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`.
144 """
145 assert init is False, 'pydantic.dataclasses.dataclass only supports init=False' 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
146 assert validate_on_init is not False, 'validate_on_init=False is no longer supported' 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
148 if sys.version_info >= (3, 10): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
149 kwargs = {'kw_only': kw_only, 'slots': slots} 1klwxmnabcdopyzqrefgJstABuvhij
150 else:
151 kwargs = {} 1DECFGHI
153 def make_pydantic_fields_compatible(cls: type[Any]) -> None: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
154 """Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only`
155 To do that, we simply change
156 `x: int = pydantic.Field(..., kw_only=True)`
157 into
158 `x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)`
159 """
160 for annotation_cls in cls.__mro__: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
161 annotations: dict[str, Any] = getattr(annotation_cls, '__annotations__', {}) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
162 for field_name in annotations: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
163 field_value = getattr(cls, field_name, None) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
164 # Process only if this is an instance of `FieldInfo`.
165 if not isinstance(field_value, FieldInfo): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
166 continue 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
168 # Initialize arguments for the standard `dataclasses.field`.
169 field_args: dict = {'default': field_value} 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
171 # Handle `kw_only` for Python 3.10+
172 if sys.version_info >= (3, 10) and field_value.kw_only: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
173 field_args['kw_only'] = True 1klwxmnabcdopyzqrefgstABuvhij
175 # Set `repr` attribute if it's explicitly specified to be not `True`.
176 if field_value.repr is not True: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
177 field_args['repr'] = field_value.repr 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
179 setattr(cls, field_name, dataclasses.field(**field_args)) 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
180 # In Python 3.9, when subclassing, information is pulled from cls.__dict__['__annotations__']
181 # for annotations, so we must make sure it's initialized before we add to it.
182 if cls.__dict__.get('__annotations__') is None: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
183 cls.__annotations__ = {} 1DECFGHI
184 cls.__annotations__[field_name] = annotations[field_name] 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
186 def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
187 """Create a Pydantic dataclass from a regular dataclass.
189 Args:
190 cls: The class to create the Pydantic dataclass from.
192 Returns:
193 A Pydantic dataclass.
194 """
195 from ._internal._utils import is_model_class 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
197 if is_model_class(cls): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
198 raise PydanticUserError( 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
199 f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
200 code='dataclass-on-model',
201 )
203 original_cls = cls 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
205 # we warn on conflicting config specifications, but only if the class doesn't have a dataclass base
206 # because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about
207 has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
208 if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
209 warn( 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
210 f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. '
211 f'The `config` specification from `dataclass` decorator will take priority.',
212 category=UserWarning,
213 stacklevel=2,
214 )
216 # if config is not explicitly provided, try to read it from the type
217 config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
218 config_wrapper = _config.ConfigWrapper(config_dict) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
219 decorators = _decorators.DecoratorInfos.build(cls) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
220 decorators.update_from_config(config_wrapper) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
222 # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
223 # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
224 # since dataclasses.dataclass will set this as the __doc__
225 original_doc = cls.__doc__ 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
227 if _pydantic_dataclasses.is_stdlib_dataclass(cls): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
228 # Vanilla dataclasses include a default docstring (representing the class signature),
229 # which we don't want to preserve.
230 original_doc = None 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
232 # We don't want to add validation to the existing std lib dataclass, so we will subclass it
233 # If the class is generic, we need to make sure the subclass also inherits from Generic
234 # with all the same parameters.
235 bases = (cls,) 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
236 if issubclass(cls, Generic): 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
237 generic_base = Generic[cls.__parameters__] # type: ignore 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
238 bases = bases + (generic_base,) 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
239 cls = types.new_class(cls.__name__, bases) 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
241 make_pydantic_fields_compatible(cls) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
243 # Respect frozen setting from dataclass constructor and fallback to config setting if not provided
244 if frozen is not None: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
245 frozen_ = frozen 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
246 if config_wrapper.frozen: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
247 # It's not recommended to define both, as the setting from the dataclass decorator will take priority.
248 warn( 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
249 f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.'
250 'This is not recommended. The `frozen` specification on `dataclass` will take priority.',
251 category=UserWarning,
252 stacklevel=2,
253 )
254 else:
255 frozen_ = config_wrapper.frozen or False 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
257 cls = dataclasses.dataclass( # type: ignore[call-overload] 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
258 cls,
259 # the value of init here doesn't affect anything except that it makes it easier to generate a signature
260 init=True,
261 repr=repr,
262 eq=eq,
263 order=order,
264 unsafe_hash=unsafe_hash,
265 frozen=frozen_,
266 **kwargs,
267 )
269 if config_wrapper.validate_assignment: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
271 @functools.wraps(cls.__setattr__) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
272 def validated_setattr(instance: Any, field: str, value: str, /) -> None: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
273 type(instance).__pydantic_validator__.validate_assignment(instance, field, value) 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
275 cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
277 if slots and not hasattr(cls, '__setstate__'): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
278 # If slots is set, `pickle` (relied on by `copy.copy()`) will use
279 # `__setattr__()` to reconstruct the dataclass. However, the custom
280 # `__setattr__()` set above relies on `validate_assignment()`, which
281 # in turn expects all the field values to be already present on the
282 # instance, resulting in attribute errors.
283 # As such, we make use of `object.__setattr__()` instead.
284 # Note that we do so only if `__setstate__()` isn't already set (this is the
285 # case if on top of `slots`, `frozen` is used).
287 # Taken from `dataclasses._dataclass_get/setstate()`:
288 def _dataclass_getstate(self: Any) -> list[Any]: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
289 return [getattr(self, f.name) for f in dataclasses.fields(self)] 1klwxmnabcdopyzqrefgstABuvhij
291 def _dataclass_setstate(self: Any, state: list[Any]) -> None: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
292 for field, value in zip(dataclasses.fields(self), state): 1klwxmnabcdopyzqrefgstABuvhij
293 object.__setattr__(self, field.name, value) 1klwxmnabcdopyzqrefgstABuvhij
295 cls.__getstate__ = _dataclass_getstate # pyright: ignore[reportAttributeAccessIssue] 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
296 cls.__setstate__ = _dataclass_setstate # pyright: ignore[reportAttributeAccessIssue] 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
298 # This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses.
299 # It should be set as early as possible:
300 cls.__is_pydantic_dataclass__ = True 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
301 cls.__pydantic_decorators__ = decorators # type: ignore 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
302 cls.__doc__ = original_doc 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
303 # Can be non-existent for dynamically created classes:
304 firstlineno = getattr(original_cls, '__firstlineno__', None) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
305 cls.__module__ = original_cls.__module__ 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
306 if sys.version_info >= (3, 13) and firstlineno is not None: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
307 # As per https://docs.python.org/3/reference/datamodel.html#type.__firstlineno__:
308 # Setting the `__module__` attribute removes the `__firstlineno__` item from the type’s dictionary.
309 original_cls.__firstlineno__ = firstlineno 1abcefgJhij
310 cls.__firstlineno__ = firstlineno 1abcefgJhij
311 cls.__qualname__ = original_cls.__qualname__ 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
312 cls.__pydantic_fields_complete__ = classmethod(_pydantic_fields_complete) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
313 cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful. 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
314 # TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models:
315 # fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function),
316 # and possibly cache it (see the `__pydantic_parent_namespace__` logic for models).
317 _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
318 return cls 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
320 return create_dataclass if _cls is None else create_dataclass(_cls) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
323def _pydantic_fields_complete(cls: type[PydanticDataclass]) -> bool: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
324 """Return whether the fields where successfully collected (i.e. type hints were successfully resolves).
326 This is a private property, not meant to be used outside Pydantic.
327 """
328 return all(field_info._complete for field_info in cls.__pydantic_fields__.values()) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
331__getattr__ = getattr_migration(__name__) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
333if sys.version_info < (3, 11): 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
334 # Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints
335 # Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable.
337 def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn: 1DEklCdFGopHIst
338 """This function does nothing but raise an error that is as similar as possible to what you'd get
339 if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just
340 to ensure typing._type_check does not error if the type hint evaluates to `InitVar[<parameter>]`.
341 """
342 raise TypeError("'InitVar' object is not callable") 1DEklCdFGopHIst
344 dataclasses.InitVar.__call__ = _call_initvar 1DEklCdFGopHIst
347def rebuild_dataclass( 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
348 cls: type[PydanticDataclass],
349 *,
350 force: bool = False,
351 raise_errors: bool = True,
352 _parent_namespace_depth: int = 2,
353 _types_namespace: MappingNamespace | None = None,
354) -> bool | None:
355 """Try to rebuild the pydantic-core schema for the dataclass.
357 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
358 the initial attempt to build the schema, and automatic rebuilding fails.
360 This is analogous to `BaseModel.model_rebuild`.
362 Args:
363 cls: The class to rebuild the pydantic-core schema for.
364 force: Whether to force the rebuilding of the schema, defaults to `False`.
365 raise_errors: Whether to raise errors, defaults to `True`.
366 _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
367 _types_namespace: The types namespace, defaults to `None`.
369 Returns:
370 Returns `None` if the schema is already "complete" and rebuilding was not required.
371 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
372 """
373 if not force and cls.__pydantic_complete__: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
374 return None 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
376 for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
377 if attr in cls.__dict__: 377 ↛ 376line 377 didn't jump to line 376 because the condition on line 377 was always true1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
378 # Deleting the validator/serializer is necessary as otherwise they can get reused in
379 # pydantic-core. Same applies for the core schema that can be reused in schema generation.
380 delattr(cls, attr) 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
382 cls.__pydantic_complete__ = False 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
384 if _types_namespace is not None: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
385 rebuild_ns = _types_namespace 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
386 elif _parent_namespace_depth > 0: 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
387 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
388 else:
389 rebuild_ns = {} 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
391 ns_resolver = _namespace_utils.NsResolver( 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
392 parent_namespace=rebuild_ns,
393 )
395 return _pydantic_dataclasses.complete_dataclass( 1DEklwxmnabcCdFGopyzqrefgHIstABuvhij
396 cls,
397 _config.ConfigWrapper(cls.__pydantic_config__, check=False),
398 raise_errors=raise_errors,
399 ns_resolver=ns_resolver,
400 # We could provide a different config instead (with `'defer_build'` set to `True`)
401 # of this explicit `_force_build` argument, but because config can come from the
402 # decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass`
403 # will overwrite `__pydantic_config__` with the provided config above:
404 _force_build=True,
405 )
408def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
409 """Whether a class is a pydantic dataclass.
411 Args:
412 class_: The class.
414 Returns:
415 `True` if the class is a pydantic dataclass, `False` otherwise.
416 """
417 try: 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
418 return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_) 1DEklwxmnabcCdFGopyzqrefgJHIstABuvhij
419 except AttributeError:
420 return False