Coverage for pydantic/_internal/_dataclasses.py: 95.59%
62 statements
« prev ^ index » next coverage.py v7.8.2, created at 2025-06-11 13:08 +0000
« prev ^ index » next coverage.py v7.8.2, created at 2025-06-11 13:08 +0000
1"""Private logic for creating pydantic dataclasses."""
3from __future__ import annotations as _annotations 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
5import typing 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
6import warnings 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
7from functools import partial 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
8from typing import Any, ClassVar 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
10from pydantic_core import ( 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
11 ArgsKwargs,
12 SchemaSerializer,
13 SchemaValidator,
14 core_schema,
15)
16from typing_extensions import TypeIs 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
18from ..errors import PydanticUndefinedAnnotation 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
19from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
20from ..warnings import PydanticDeprecatedSince20 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
21from . import _config, _decorators 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
22from ._fields import collect_dataclass_fields 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
23from ._generate_schema import GenerateSchema, InvalidSchemaError 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
24from ._generics import get_standard_typevars_map 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
25from ._mock_val_ser import set_dataclass_mocks 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
26from ._namespace_utils import NsResolver 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
27from ._signature import generate_pydantic_signature 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
28from ._utils import LazyClassAttribute 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
30if typing.TYPE_CHECKING: 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
31 from _typeshed import DataclassInstance as StandardDataclass
33 from ..config import ConfigDict
34 from ..fields import FieldInfo
36 class PydanticDataclass(StandardDataclass, typing.Protocol):
37 """A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass.
39 Attributes:
40 __pydantic_config__: Pydantic-specific configuration settings for the dataclass.
41 __pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields.
42 __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
43 __pydantic_decorators__: Metadata containing the decorators defined on the dataclass.
44 __pydantic_fields__: Metadata about the fields defined on the dataclass.
45 __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass.
46 __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass.
47 """
49 __pydantic_config__: ClassVar[ConfigDict]
50 __pydantic_complete__: ClassVar[bool]
51 __pydantic_core_schema__: ClassVar[core_schema.CoreSchema]
52 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos]
53 __pydantic_fields__: ClassVar[dict[str, FieldInfo]]
54 __pydantic_serializer__: ClassVar[SchemaSerializer]
55 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
57else:
58 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
59 # and https://youtrack.jetbrains.com/issue/PY-51428
60 DeprecationWarning = PydanticDeprecatedSince20 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
63def set_dataclass_fields( 1abcdefghijklmnopqrstuvJwxyzABCDEFG
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) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
76 fields = collect_dataclass_fields( 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
77 cls, ns_resolver=ns_resolver, typevars_map=typevars_map, config_wrapper=config_wrapper
78 )
80 cls.__pydantic_fields__ = fields # type: ignore 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
83def complete_dataclass( 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
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__ 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
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: 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
117 __tracebackhide__ = True 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
118 s = __dataclass_self__ 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
119 s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
121 __init__.__qualname__ = f'{cls.__qualname__}.__init__' 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
123 cls.__init__ = __init__ # type: ignore 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
124 cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
126 set_dataclass_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
128 if not _force_build and config_wrapper.defer_build: 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
129 set_dataclass_mocks(cls) 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
130 return False 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
132 if hasattr(cls, '__post_init_post_parse__'): 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
133 warnings.warn( 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
134 'Support for `__post_init_post_parse__` has been dropped, the method will not be called', DeprecationWarning
135 )
137 typevars_map = get_standard_typevars_map(cls) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
138 gen_schema = GenerateSchema( 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
139 config_wrapper,
140 ns_resolver=ns_resolver,
141 typevars_map=typevars_map,
142 )
144 # set __signature__ attr only for the class, but not for its instances
145 # (because instances can define `__call__`, and `inspect.signature` shouldn't
146 # use the `__signature__` attribute and instead generate from `__call__`).
147 cls.__signature__ = LazyClassAttribute( 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
148 '__signature__',
149 partial(
150 generate_pydantic_signature,
151 # It's important that we reference the `original_init` here,
152 # as it is the one synthesized by the stdlib `dataclass` module:
153 init=original_init,
154 fields=cls.__pydantic_fields__, # type: ignore
155 validate_by_name=config_wrapper.validate_by_name,
156 extra=config_wrapper.extra,
157 is_dataclass=True,
158 ),
159 )
161 try: 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
162 schema = gen_schema.generate_schema(cls) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
163 except PydanticUndefinedAnnotation as e: 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
164 if raise_errors: 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
165 raise 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
166 set_dataclass_mocks(cls, f'`{e.name}`') 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
167 return False 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG
169 core_config = config_wrapper.core_config(title=cls.__name__) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
171 try: 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
172 schema = gen_schema.clean_schema(schema) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
173 except InvalidSchemaError:
174 set_dataclass_mocks(cls)
175 return False
177 # We are about to set all the remaining required properties expected for this cast;
178 # __pydantic_decorators__ and __pydantic_fields__ should already be set
179 cls = typing.cast('type[PydanticDataclass]', cls) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
181 cls.__pydantic_core_schema__ = schema 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
182 cls.__pydantic_validator__ = create_schema_validator( 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
183 schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings
184 )
185 cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config) 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
186 cls.__pydantic_complete__ = True 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
187 return True 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
190def is_stdlib_dataclass(cls: type[Any], /) -> TypeIs[type[StandardDataclass]]: 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG
191 """Returns `True` if the class is a stdlib dataclass and *not* a Pydantic dataclass.
193 Unlike the stdlib `dataclasses.is_dataclass()` function, this does *not* include subclasses
194 of a dataclass that are themselves not dataclasses.
196 Args:
197 cls: The class.
199 Returns:
200 `True` if the class is a stdlib dataclass, `False` otherwise.
201 """
202 return '__dataclass_fields__' in cls.__dict__ and not hasattr(cls, '__pydantic_validator__') 1abcdefghijkHIlmnopqrstuvJwxyzABCDEFG