Coverage for pydantic/main.py: 98.10%
550 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-02 16:20 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-02 16:20 +0000
1"""Logic for creating models."""
3# Because `dict` is in the local namespace of the `BaseModel` class, we use `Dict` for annotations.
4# TODO v3 fallback to `dict` when the deprecated `dict` method gets removed.
5# ruff: noqa: UP035
7from __future__ import annotations as _annotations 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
9import operator 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
10import sys 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
11import types 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
12import typing 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
13import warnings 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
14from collections.abc import Generator, Mapping 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
15from copy import copy, deepcopy 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
16from functools import cached_property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
17from typing import ( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
18 TYPE_CHECKING,
19 Any,
20 Callable,
21 ClassVar,
22 Dict,
23 Literal,
24 TypeVar,
25 Union,
26 cast,
27 overload,
28)
30import pydantic_core 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
31import typing_extensions 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
32from pydantic_core import PydanticUndefined, ValidationError 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
33from typing_extensions import Self, TypeAlias, Unpack 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
35from . import PydanticDeprecatedSince20, PydanticDeprecatedSince211 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
36from ._internal import ( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
37 _config,
38 _decorators,
39 _fields,
40 _forward_ref,
41 _generics,
42 _mock_val_ser,
43 _model_construction,
44 _namespace_utils,
45 _repr,
46 _typing_extra,
47 _utils,
48)
49from ._migration import getattr_migration 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
50from .aliases import AliasChoices, AliasPath 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
51from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
52from .config import ConfigDict 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
53from .errors import PydanticUndefinedAnnotation, PydanticUserError 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
54from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
55from .plugin._schema_validator import PluggableSchemaValidator 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
57if TYPE_CHECKING: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
58 from inspect import Signature
59 from pathlib import Path
61 from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator
63 from ._internal._namespace_utils import MappingNamespace
64 from ._internal._utils import AbstractSetIntStr, MappingIntStrAny
65 from .deprecated.parse import Protocol as DeprecatedParseProtocol
66 from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr 1r
67else:
68 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
69 # and https://youtrack.jetbrains.com/issue/PY-51428
70 DeprecationWarning = PydanticDeprecatedSince20 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
72__all__ = 'BaseModel', 'create_model' 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
74# Keep these type aliases available at runtime:
75TupleGenerator: TypeAlias = Generator[tuple[str, Any], None, None] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
76# NOTE: In reality, `bool` should be replaced by `Literal[True]` but mypy fails to correctly apply bidirectional
77# type inference (e.g. when using `{'a': {'b': True}}`):
78# NOTE: Keep this type alias in sync with the stub definition in `pydantic-core`:
79IncEx: TypeAlias = Union[set[int], set[str], Mapping[int, Union['IncEx', bool]], Mapping[str, Union['IncEx', bool]]] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
81_object_setattr = _model_construction.object_setattr 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
84def _check_frozen(model_cls: type[BaseModel], name: str, value: Any) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
85 if model_cls.model_config.get('frozen'): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
86 error_type = 'frozen_instance' 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
87 elif getattr(model_cls.__pydantic_fields__.get(name), 'frozen', False): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
88 error_type = 'frozen_field' 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
89 else:
90 return 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
92 raise ValidationError.from_exception_data( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
93 model_cls.__name__, [{'type': error_type, 'loc': (name,), 'input': value}]
94 )
97def _model_field_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
98 model.__dict__[name] = val 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
99 model.__pydantic_fields_set__.add(name) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
102def _private_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
103 if getattr(model, '__pydantic_private__', None) is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
104 # While the attribute should be present at this point, this may not be the case if
105 # users do unusual stuff with `model_post_init()` (which is where the `__pydantic_private__`
106 # is initialized, by wrapping the user-defined `model_post_init()`), e.g. if they mock
107 # the `model_post_init()` call. Ideally we should find a better way to init private attrs.
108 object.__setattr__(model, '__pydantic_private__', {}) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
109 model.__pydantic_private__[name] = val # pyright: ignore[reportOptionalSubscript] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
112_SIMPLE_SETATTR_HANDLERS: Mapping[str, Callable[[BaseModel, str, Any], None]] = { 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
113 'model_field': _model_field_setattr_handler,
114 'validate_assignment': lambda model, name, val: model.__pydantic_validator__.validate_assignment(model, name, val), # pyright: ignore[reportAssignmentType]
115 'private': _private_setattr_handler,
116 'cached_property': lambda model, name, val: model.__dict__.__setitem__(name, val),
117 'extra_known': lambda model, name, val: _object_setattr(model, name, val),
118}
121class BaseModel(metaclass=_model_construction.ModelMetaclass): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
122 """!!! abstract "Usage Documentation"
123 [Models](../concepts/models.md)
125 A base class for creating Pydantic models.
127 Attributes:
128 __class_vars__: The names of the class variables defined on the model.
129 __private_attributes__: Metadata about the private attributes of the model.
130 __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.
132 __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
133 __pydantic_core_schema__: The core schema of the model.
134 __pydantic_custom_init__: Whether the model has a custom `__init__` function.
135 __pydantic_decorators__: Metadata containing the decorators defined on the model.
136 This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.
137 __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to
138 __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
139 __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
140 __pydantic_post_init__: The name of the post-init method for the model, if defined.
141 __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].
142 __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.
143 __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.
145 __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
146 __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.
148 __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]
149 is set to `'allow'`.
150 __pydantic_fields_set__: The names of fields explicitly set during instantiation.
151 __pydantic_private__: Values of private attributes set on the model instance.
152 """
154 # Note: Many of the below class vars are defined in the metaclass, but we define them here for type checking purposes.
156 model_config: ClassVar[ConfigDict] = ConfigDict() 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
157 """ 1puqvcladerwxyzmnfghJsAtBiobjk
158 Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict].
159 """
161 __class_vars__: ClassVar[set[str]] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
162 """The names of the class variables defined on the model.""" 1puqvcladerwxyzmnfghJsAtBiobjk
164 __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]] # noqa: UP006 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
165 """Metadata about the private attributes of the model.""" 1puqvcladerwxyzmnfghJsAtBiobjk
167 __signature__: ClassVar[Signature] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
168 """The synthesized `__init__` [`Signature`][inspect.Signature] of the model.""" 1puqvcladerwxyzmnfghJsAtBiobjk
170 __pydantic_complete__: ClassVar[bool] = False 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
171 """Whether model building is completed, or if there are still undefined fields.""" 1puqvcladerwxyzmnfghJsAtBiobjk
173 __pydantic_core_schema__: ClassVar[CoreSchema] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
174 """The core schema of the model.""" 1puqvcladerwxyzmnfghJsAtBiobjk
176 __pydantic_custom_init__: ClassVar[bool] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
177 """Whether the model has a custom `__init__` method.""" 1puqvcladerwxyzmnfghJsAtBiobjk
179 # Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation.
180 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos() 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
181 """Metadata containing the decorators defined on the model. 1puqvcladerwxyzmnfghJsAtBiobjk
182 This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1."""
184 __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
185 """Metadata for generic models; contains data used for a similar purpose to 1puqvcladerwxyzmnfghJsAtBiobjk
186 __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these."""
188 __pydantic_parent_namespace__: ClassVar[Dict[str, Any] | None] = None # noqa: UP006 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
189 """Parent namespace of the model, used for automatic rebuilding of models.""" 1puqvcladerwxyzmnfghJsAtBiobjk
191 __pydantic_post_init__: ClassVar[None | Literal['model_post_init']] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
192 """The name of the post-init method for the model, if defined.""" 1puqvcladerwxyzmnfghJsAtBiobjk
194 __pydantic_root_model__: ClassVar[bool] = False 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
195 """Whether the model is a [`RootModel`][pydantic.root_model.RootModel].""" 1puqvcladerwxyzmnfghJsAtBiobjk
197 __pydantic_serializer__: ClassVar[SchemaSerializer] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
198 """The `pydantic-core` `SchemaSerializer` used to dump instances of the model.""" 1puqvcladerwxyzmnfghJsAtBiobjk
200 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
201 """The `pydantic-core` `SchemaValidator` used to validate instances of the model.""" 1puqvcladerwxyzmnfghJsAtBiobjk
203 __pydantic_fields__: ClassVar[Dict[str, FieldInfo]] # noqa: UP006 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
204 """A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects. 1puqvcladerwxyzmnfghJsAtBiobjk
205 This replaces `Model.__fields__` from Pydantic V1.
206 """
208 __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]] # noqa: UP006 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
209 """`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`""" 1puqvcladerwxyzmnfghJsAtBiobjk
211 __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] # noqa: UP006 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
212 """A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.""" 1puqvcladerwxyzmnfghJsAtBiobjk
214 __pydantic_extra__: dict[str, Any] | None = _model_construction.NoInitField(init=False) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
215 """A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`.""" 1puqvcladerwxyzmnfghJsAtBiobjk
217 __pydantic_fields_set__: set[str] = _model_construction.NoInitField(init=False) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
218 """The names of fields explicitly set during instantiation.""" 1puqvcladerwxyzmnfghJsAtBiobjk
220 __pydantic_private__: dict[str, Any] | None = _model_construction.NoInitField(init=False) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
221 """Values of private attributes set on the model instance.""" 1puqvcladerwxyzmnfghJsAtBiobjk
223 if not TYPE_CHECKING: 223 ↛ 241line 223 didn't jump to line 241 because the condition on line 223 was always true1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
224 # Prevent `BaseModel` from being instantiated directly
225 # (defined in an `if not TYPE_CHECKING` block for clarity and to avoid type checking errors):
226 __pydantic_core_schema__ = _mock_val_ser.MockCoreSchema( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
227 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
228 code='base-model-instantiated',
229 )
230 __pydantic_validator__ = _mock_val_ser.MockValSer( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
231 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
232 val_or_ser='validator',
233 code='base-model-instantiated',
234 )
235 __pydantic_serializer__ = _mock_val_ser.MockValSer( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
236 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
237 val_or_ser='serializer',
238 code='base-model-instantiated',
239 )
241 __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
243 def __init__(self, /, **data: Any) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
244 """Create a new model by parsing and validating input data from keyword arguments.
246 Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
247 validated to form a valid model.
249 `self` is explicitly positional-only to allow `self` as a field name.
250 """
251 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
252 __tracebackhide__ = True 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
253 validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
254 if self is not validated_self: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
255 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
256 'A custom validator is returning a value other than `self`.\n'
257 "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
258 'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
259 stacklevel=2,
260 )
262 # The following line sets a flag that we use to determine when `__init__` gets overridden by the user
263 __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
265 @_utils.deprecated_instance_property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
266 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
267 def model_fields(cls) -> dict[str, FieldInfo]: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
268 """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.
270 !!! warning
271 Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
272 Instead, you should access this attribute from the model class.
273 """
274 return getattr(cls, '__pydantic_fields__', {}) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
276 @_utils.deprecated_instance_property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
277 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
278 def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
279 """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.
281 !!! warning
282 Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
283 Instead, you should access this attribute from the model class.
284 """
285 return getattr(cls, '__pydantic_computed_fields__', {}) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
287 @property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
288 def model_extra(self) -> dict[str, Any] | None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
289 """Get extra fields set during validation.
291 Returns:
292 A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
293 """
294 return self.__pydantic_extra__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
296 @property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
297 def model_fields_set(self) -> set[str]: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
298 """Returns the set of fields that have been explicitly set on this model instance.
300 Returns:
301 A set of strings representing the fields that have been set,
302 i.e. that were not filled from defaults.
303 """
304 return self.__pydantic_fields_set__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
306 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
307 def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: C901 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
308 """Creates a new instance of the `Model` class with validated data.
310 Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
311 Default values are respected, but no other validation is performed.
313 !!! note
314 `model_construct()` generally respects the `model_config.extra` setting on the provided model.
315 That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
316 and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
317 Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
318 an error if extra values are passed, but they will be ignored.
320 Args:
321 _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
322 this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
323 Otherwise, the field names from the `values` argument will be used.
324 values: Trusted or pre-validated data dictionary.
326 Returns:
327 A new instance of the `Model` class with validated data.
328 """
329 m = cls.__new__(cls) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
330 fields_values: dict[str, Any] = {} 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
331 fields_set = set() 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
333 for name, field in cls.__pydantic_fields__.items(): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
334 if field.alias is not None and field.alias in values: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
335 fields_values[name] = values.pop(field.alias) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
336 fields_set.add(name) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
338 if (name not in fields_set) and (field.validation_alias is not None): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
339 validation_aliases: list[str | AliasPath] = ( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
340 field.validation_alias.choices
341 if isinstance(field.validation_alias, AliasChoices)
342 else [field.validation_alias]
343 )
345 for alias in validation_aliases: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
346 if isinstance(alias, str) and alias in values: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
347 fields_values[name] = values.pop(alias) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
348 fields_set.add(name) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
349 break 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
350 elif isinstance(alias, AliasPath): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
351 value = alias.search_dict_for_path(values) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
352 if value is not PydanticUndefined: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
353 fields_values[name] = value 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
354 fields_set.add(name) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
355 break 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
357 if name not in fields_set: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
358 if name in values: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
359 fields_values[name] = values.pop(name) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
360 fields_set.add(name) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
361 elif not field.is_required(): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
362 fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
363 if _fields_set is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
364 _fields_set = fields_set 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
366 _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
367 _object_setattr(m, '__dict__', fields_values) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
368 _object_setattr(m, '__pydantic_fields_set__', _fields_set) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
369 if not cls.__pydantic_root_model__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
370 _object_setattr(m, '__pydantic_extra__', _extra) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
372 if cls.__pydantic_post_init__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
373 m.model_post_init(None) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
374 # update private attributes with values set
375 if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
376 for k, v in values.items(): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
377 if k in m.__private_attributes__: 377 ↛ 376line 377 didn't jump to line 376 because the condition on line 377 was always true1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
378 m.__pydantic_private__[k] = v 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
380 elif not cls.__pydantic_root_model__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
381 # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
382 # Since it doesn't, that means that `__pydantic_private__` should be set to None
383 _object_setattr(m, '__pydantic_private__', None) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
385 return m 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
387 def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
388 """!!! abstract "Usage Documentation"
389 [`model_copy`](../concepts/serialization.md#model_copy)
391 Returns a copy of the model.
393 !!! note
394 The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
395 might have unexpected side effects if you store anything in it, on top of the model
396 fields (e.g. the value of [cached properties][functools.cached_property]).
398 Args:
399 update: Values to change/add in the new model. Note: the data is not validated
400 before creating the new model. You should trust this data.
401 deep: Set to `True` to make a deep copy of the model.
403 Returns:
404 New model instance.
405 """
406 copied = self.__deepcopy__() if deep else self.__copy__() 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
407 if update: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
408 if self.model_config.get('extra') == 'allow': 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
409 for k, v in update.items(): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
410 if k in self.__pydantic_fields__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
411 copied.__dict__[k] = v 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
412 else:
413 if copied.__pydantic_extra__ is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
414 copied.__pydantic_extra__ = {} 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
415 copied.__pydantic_extra__[k] = v 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
416 else:
417 copied.__dict__.update(update) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
418 copied.__pydantic_fields_set__.update(update.keys()) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
419 return copied 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
421 def model_dump( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
422 self,
423 *,
424 mode: Literal['json', 'python'] | str = 'python',
425 include: IncEx | None = None,
426 exclude: IncEx | None = None,
427 context: Any | None = None,
428 by_alias: bool | None = None,
429 exclude_unset: bool = False,
430 exclude_defaults: bool = False,
431 exclude_none: bool = False,
432 round_trip: bool = False,
433 warnings: bool | Literal['none', 'warn', 'error'] = True,
434 fallback: Callable[[Any], Any] | None = None,
435 serialize_as_any: bool = False,
436 ) -> dict[str, Any]:
437 """!!! abstract "Usage Documentation"
438 [`model_dump`](../concepts/serialization.md#modelmodel_dump)
440 Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
442 Args:
443 mode: The mode in which `to_python` should run.
444 If mode is 'json', the output will only contain JSON serializable types.
445 If mode is 'python', the output may contain non-JSON-serializable Python objects.
446 include: A set of fields to include in the output.
447 exclude: A set of fields to exclude from the output.
448 context: Additional context to pass to the serializer.
449 by_alias: Whether to use the field's alias in the dictionary key if defined.
450 exclude_unset: Whether to exclude fields that have not been explicitly set.
451 exclude_defaults: Whether to exclude fields that are set to their default value.
452 exclude_none: Whether to exclude fields that have a value of `None`.
453 round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
454 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
455 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
456 fallback: A function to call when an unknown value is encountered. If not provided,
457 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
458 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
460 Returns:
461 A dictionary representation of the model.
462 """
463 return self.__pydantic_serializer__.to_python( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
464 self,
465 mode=mode,
466 by_alias=by_alias,
467 include=include,
468 exclude=exclude,
469 context=context,
470 exclude_unset=exclude_unset,
471 exclude_defaults=exclude_defaults,
472 exclude_none=exclude_none,
473 round_trip=round_trip,
474 warnings=warnings,
475 fallback=fallback,
476 serialize_as_any=serialize_as_any,
477 )
479 def model_dump_json( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
480 self,
481 *,
482 indent: int | None = None,
483 include: IncEx | None = None,
484 exclude: IncEx | None = None,
485 context: Any | None = None,
486 by_alias: bool | None = None,
487 exclude_unset: bool = False,
488 exclude_defaults: bool = False,
489 exclude_none: bool = False,
490 round_trip: bool = False,
491 warnings: bool | Literal['none', 'warn', 'error'] = True,
492 fallback: Callable[[Any], Any] | None = None,
493 serialize_as_any: bool = False,
494 ) -> str:
495 """!!! abstract "Usage Documentation"
496 [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json)
498 Generates a JSON representation of the model using Pydantic's `to_json` method.
500 Args:
501 indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
502 include: Field(s) to include in the JSON output.
503 exclude: Field(s) to exclude from the JSON output.
504 context: Additional context to pass to the serializer.
505 by_alias: Whether to serialize using field aliases.
506 exclude_unset: Whether to exclude fields that have not been explicitly set.
507 exclude_defaults: Whether to exclude fields that are set to their default value.
508 exclude_none: Whether to exclude fields that have a value of `None`.
509 round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
510 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
511 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
512 fallback: A function to call when an unknown value is encountered. If not provided,
513 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
514 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
516 Returns:
517 A JSON string representation of the model.
518 """
519 return self.__pydantic_serializer__.to_json( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
520 self,
521 indent=indent,
522 include=include,
523 exclude=exclude,
524 context=context,
525 by_alias=by_alias,
526 exclude_unset=exclude_unset,
527 exclude_defaults=exclude_defaults,
528 exclude_none=exclude_none,
529 round_trip=round_trip,
530 warnings=warnings,
531 fallback=fallback,
532 serialize_as_any=serialize_as_any,
533 ).decode()
535 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
536 def model_json_schema( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
537 cls,
538 by_alias: bool = True,
539 ref_template: str = DEFAULT_REF_TEMPLATE,
540 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
541 mode: JsonSchemaMode = 'validation',
542 ) -> dict[str, Any]:
543 """Generates a JSON schema for a model class.
545 Args:
546 by_alias: Whether to use attribute aliases or not.
547 ref_template: The reference template.
548 schema_generator: To override the logic used to generate the JSON schema, as a subclass of
549 `GenerateJsonSchema` with your desired modifications
550 mode: The mode in which to generate the schema.
552 Returns:
553 The JSON schema for the given model class.
554 """
555 return model_json_schema( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
556 cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode
557 )
559 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
560 def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
561 """Compute the class name for parametrizations of generic classes.
563 This method can be overridden to achieve a custom naming scheme for generic BaseModels.
565 Args:
566 params: Tuple of types of the class. Given a generic class
567 `Model` with 2 type variables and a concrete model `Model[str, int]`,
568 the value `(str, int)` would be passed to `params`.
570 Returns:
571 String representing the new class where `params` are passed to `cls` as type variables.
573 Raises:
574 TypeError: Raised when trying to generate concrete names for non-generic models.
575 """
576 if not issubclass(cls, typing.Generic): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
577 raise TypeError('Concrete names should only be generated for generic models.') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
579 # Any strings received should represent forward references, so we handle them specially below.
580 # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
581 # we may be able to remove this special case.
582 param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
583 params_component = ', '.join(param_names) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
584 return f'{cls.__name__}[{params_component}]' 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
586 def model_post_init(self, context: Any, /) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
587 """Override this method to perform additional initialization after `__init__` and `model_construct`.
588 This is useful if you want to do some validation that requires the entire model to be initialized.
589 """
590 pass 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
592 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
593 def model_rebuild( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
594 cls,
595 *,
596 force: bool = False,
597 raise_errors: bool = True,
598 _parent_namespace_depth: int = 2,
599 _types_namespace: MappingNamespace | None = None,
600 ) -> bool | None:
601 """Try to rebuild the pydantic-core schema for the model.
603 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
604 the initial attempt to build the schema, and automatic rebuilding fails.
606 Args:
607 force: Whether to force the rebuilding of the model schema, defaults to `False`.
608 raise_errors: Whether to raise errors, defaults to `True`.
609 _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
610 _types_namespace: The types namespace, defaults to `None`.
612 Returns:
613 Returns `None` if the schema is already "complete" and rebuilding was not required.
614 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
615 """
616 already_complete = cls.__pydantic_complete__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
617 if already_complete and not force: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
618 return None 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
620 cls.__pydantic_complete__ = False 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
622 for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
623 if attr in cls.__dict__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
624 # Deleting the validator/serializer is necessary as otherwise they can get reused in
625 # pydantic-core. Same applies for the core schema that can be reused in schema generation.
626 delattr(cls, attr) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
628 if _types_namespace is not None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
629 rebuild_ns = _types_namespace 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
630 elif _parent_namespace_depth > 0: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
631 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
632 else:
633 rebuild_ns = {} 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
635 parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
637 ns_resolver = _namespace_utils.NsResolver( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
638 parent_namespace={**rebuild_ns, **parent_ns},
639 )
641 return _model_construction.complete_model_class( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
642 cls,
643 _config.ConfigWrapper(cls.model_config, check=False),
644 ns_resolver,
645 raise_errors=raise_errors,
646 # If the model was already complete, we don't need to call the hook again.
647 call_on_complete_hook=not already_complete,
648 )
650 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
651 def model_validate( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
652 cls,
653 obj: Any,
654 *,
655 strict: bool | None = None,
656 from_attributes: bool | None = None,
657 context: Any | None = None,
658 by_alias: bool | None = None,
659 by_name: bool | None = None,
660 ) -> Self:
661 """Validate a pydantic model instance.
663 Args:
664 obj: The object to validate.
665 strict: Whether to enforce types strictly.
666 from_attributes: Whether to extract data from object attributes.
667 context: Additional context to pass to the validator.
668 by_alias: Whether to use the field's alias when validating against the provided input data.
669 by_name: Whether to use the field's name when validating against the provided input data.
671 Raises:
672 ValidationError: If the object could not be validated.
674 Returns:
675 The validated model instance.
676 """
677 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
678 __tracebackhide__ = True 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
680 if by_alias is False and by_name is not True: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
681 raise PydanticUserError( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
682 'At least one of `by_alias` or `by_name` must be set to True.',
683 code='validate-by-alias-and-name-false',
684 )
686 return cls.__pydantic_validator__.validate_python( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
687 obj, strict=strict, from_attributes=from_attributes, context=context, by_alias=by_alias, by_name=by_name
688 )
690 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
691 def model_validate_json( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
692 cls,
693 json_data: str | bytes | bytearray,
694 *,
695 strict: bool | None = None,
696 context: Any | None = None,
697 by_alias: bool | None = None,
698 by_name: bool | None = None,
699 ) -> Self:
700 """!!! abstract "Usage Documentation"
701 [JSON Parsing](../concepts/json.md#json-parsing)
703 Validate the given JSON data against the Pydantic model.
705 Args:
706 json_data: The JSON data to validate.
707 strict: Whether to enforce types strictly.
708 context: Extra variables to pass to the validator.
709 by_alias: Whether to use the field's alias when validating against the provided input data.
710 by_name: Whether to use the field's name when validating against the provided input data.
712 Returns:
713 The validated Pydantic model.
715 Raises:
716 ValidationError: If `json_data` is not a JSON string or the object could not be validated.
717 """
718 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
719 __tracebackhide__ = True 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
721 if by_alias is False and by_name is not True: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
722 raise PydanticUserError( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
723 'At least one of `by_alias` or `by_name` must be set to True.',
724 code='validate-by-alias-and-name-false',
725 )
727 return cls.__pydantic_validator__.validate_json( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
728 json_data, strict=strict, context=context, by_alias=by_alias, by_name=by_name
729 )
731 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
732 def model_validate_strings( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
733 cls,
734 obj: Any,
735 *,
736 strict: bool | None = None,
737 context: Any | None = None,
738 by_alias: bool | None = None,
739 by_name: bool | None = None,
740 ) -> Self:
741 """Validate the given object with string data against the Pydantic model.
743 Args:
744 obj: The object containing string data to validate.
745 strict: Whether to enforce types strictly.
746 context: Extra variables to pass to the validator.
747 by_alias: Whether to use the field's alias when validating against the provided input data.
748 by_name: Whether to use the field's name when validating against the provided input data.
750 Returns:
751 The validated Pydantic model.
752 """
753 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
754 __tracebackhide__ = True 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
756 if by_alias is False and by_name is not True: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
757 raise PydanticUserError( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
758 'At least one of `by_alias` or `by_name` must be set to True.',
759 code='validate-by-alias-and-name-false',
760 )
762 return cls.__pydantic_validator__.validate_strings( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
763 obj, strict=strict, context=context, by_alias=by_alias, by_name=by_name
764 )
766 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
767 def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
768 # This warning is only emitted when calling `super().__get_pydantic_core_schema__` from a model subclass.
769 # In the generate schema logic, this method (`BaseModel.__get_pydantic_core_schema__`) is special cased to
770 # *not* be called if not overridden.
771 warnings.warn(
772 'The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated. If you are calling '
773 '`super().__get_pydantic_core_schema__` when overriding the method on a Pydantic model, consider using '
774 '`handler(source)` instead. However, note that overriding this method on models can lead to unexpected '
775 'side effects.',
776 PydanticDeprecatedSince211,
777 stacklevel=2,
778 )
779 # Logic copied over from `GenerateSchema._model_schema`:
780 schema = cls.__dict__.get('__pydantic_core_schema__')
781 if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema):
782 return cls.__pydantic_core_schema__
784 return handler(source)
786 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
787 def __get_pydantic_json_schema__( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
788 cls,
789 core_schema: CoreSchema,
790 handler: GetJsonSchemaHandler,
791 /,
792 ) -> JsonSchemaValue:
793 """Hook into generating the model's JSON schema.
795 Args:
796 core_schema: A `pydantic-core` CoreSchema.
797 You can ignore this argument and call the handler with a new CoreSchema,
798 wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
799 or just call the handler with the original schema.
800 handler: Call into Pydantic's internal JSON schema generation.
801 This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
802 generation fails.
803 Since this gets called by `BaseModel.model_json_schema` you can override the
804 `schema_generator` argument to that function to change JSON schema generation globally
805 for a type.
807 Returns:
808 A JSON schema, as a Python object.
809 """
810 return handler(core_schema) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
812 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
813 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
814 """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
815 only after basic class initialization is complete. In particular, attributes like `model_fields` will
816 be present when this is called, but forward annotations are not guaranteed to be resolved yet,
817 meaning that creating an instance of the class may fail.
819 This is necessary because `__init_subclass__` will always be called by `type.__new__`,
820 and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
821 `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
823 This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
824 any kwargs passed to the class definition that aren't used internally by Pydantic.
826 Args:
827 **kwargs: Any keyword arguments passed to the class definition that aren't used internally
828 by Pydantic.
830 Note:
831 You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
832 instead, which is called once the class and its fields are fully initialized and ready for validation.
833 """
834 pass 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
836 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
837 def __pydantic_on_complete__(cls) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
838 """This is called once the class and its fields are fully initialized and ready to be used.
840 This typically happens when the class is created (just before
841 [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
842 except when forward annotations are used that could not immediately be resolved.
843 In that case, it will be called later, when the model is rebuilt automatically or explicitly using
844 [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
845 """
846 pass 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
848 def __class_getitem__( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
849 cls, typevar_values: type[Any] | tuple[type[Any], ...]
850 ) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef:
851 cached = _generics.get_cached_generic_type_early(cls, typevar_values) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
852 if cached is not None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
853 return cached 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
855 if cls is BaseModel: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
856 raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
857 if not hasattr(cls, '__parameters__'): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
858 raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
859 if not cls.__pydantic_generic_metadata__['parameters'] and typing.Generic not in cls.__bases__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
860 raise TypeError(f'{cls} is not a generic class') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
862 if not isinstance(typevar_values, tuple): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
863 typevar_values = (typevar_values,) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
865 # For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`,
866 # this gives us `{T: str, U: bool, V: int}`:
867 typevars_map = _generics.map_generic_model_arguments(cls, typevar_values) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
868 # We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`):
869 typevar_values = tuple(v for v in typevars_map.values()) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
871 if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
872 submodel = cls # if arguments are equal to parameters it's the same object 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
873 _generics.set_cached_generic_type(cls, typevar_values, submodel) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
874 else:
875 parent_args = cls.__pydantic_generic_metadata__['args'] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
876 if not parent_args: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
877 args = typevar_values 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
878 else:
879 args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
881 origin = cls.__pydantic_generic_metadata__['origin'] or cls 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
882 model_name = origin.model_parametrized_name(args) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
883 params = tuple( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
884 {param: None for param in _generics.iter_contained_typevars(typevars_map.values())}
885 ) # use dict as ordered set
887 with _generics.generic_recursion_self_type(origin, args) as maybe_self_type: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
888 cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
889 if cached is not None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
890 return cached 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
892 if maybe_self_type is not None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
893 return maybe_self_type 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
895 # Attempt to rebuild the origin in case new types have been defined
896 try: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
897 # depth 2 gets you above this __class_getitem__ call.
898 # Note that we explicitly provide the parent ns, otherwise
899 # `model_rebuild` will use the parent ns no matter if it is the ns of a module.
900 # We don't want this here, as this has unexpected effects when a model
901 # is being parametrized during a forward annotation evaluation.
902 parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
903 origin.model_rebuild(_types_namespace=parent_ns) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
904 except PydanticUndefinedAnnotation: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
905 # It's okay if it fails, it just means there are still undefined types
906 # that could be evaluated later.
907 pass 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
909 submodel = _generics.create_generic_submodel(model_name, origin, args, params) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
911 _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
913 return submodel 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
915 def __copy__(self) -> Self: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
916 """Returns a shallow copy of the model."""
917 cls = type(self) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
918 m = cls.__new__(cls) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
919 _object_setattr(m, '__dict__', copy(self.__dict__)) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
920 _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__)) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
921 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
923 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
924 _object_setattr(m, '__pydantic_private__', None) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
925 else:
926 _object_setattr( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
927 m,
928 '__pydantic_private__',
929 {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
930 )
932 return m 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
934 def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
935 """Returns a deep copy of the model."""
936 cls = type(self) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
937 m = cls.__new__(cls) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
938 _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
939 _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo)) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
940 # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
941 # and attempting a deepcopy would be marginally slower.
942 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
944 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
945 _object_setattr(m, '__pydantic_private__', None) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
946 else:
947 _object_setattr( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
948 m,
949 '__pydantic_private__',
950 deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
951 )
953 return m 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
955 if not TYPE_CHECKING: 955 ↛ 1091line 955 didn't jump to line 1091 because the condition on line 955 was always true1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
956 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
957 # The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643
959 def __getattr__(self, item: str) -> Any: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
960 private_attributes = object.__getattribute__(self, '__private_attributes__') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
961 if item in private_attributes: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
962 attribute = private_attributes[item] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
963 if hasattr(attribute, '__get__'): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
964 return attribute.__get__(self, type(self)) # type: ignore 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
966 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
967 # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
968 return self.__pydantic_private__[item] # type: ignore 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
969 except KeyError as exc: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
970 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
971 else:
972 # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
973 # See `BaseModel.__repr_args__` for more details
974 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
975 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
976 except AttributeError: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
977 pydantic_extra = None 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
979 if pydantic_extra: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
980 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
981 return pydantic_extra[item] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
982 except KeyError as exc: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
983 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
984 else:
985 if hasattr(self.__class__, item): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
986 return super().__getattribute__(item) # Raises AttributeError if appropriate 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
987 else:
988 # this is the current error
989 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
991 def __setattr__(self, name: str, value: Any) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
992 if (setattr_handler := self.__pydantic_setattr_handlers__.get(name)) is not None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
993 setattr_handler(self, name, value) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
994 # if None is returned from _setattr_handler, the attribute was set directly
995 elif (setattr_handler := self._setattr_handler(name, value)) is not None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
996 setattr_handler(self, name, value) # call here to not memo on possibly unknown fields 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
997 self.__pydantic_setattr_handlers__[name] = setattr_handler # memoize the handler for faster access 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
999 def _setattr_handler(self, name: str, value: Any) -> Callable[[BaseModel, str, Any], None] | None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1000 """Get a handler for setting an attribute on the model instance.
1002 Returns:
1003 A handler for setting an attribute on the model instance. Used for memoization of the handler.
1004 Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`
1005 Returns `None` when memoization is not safe, then the attribute is set directly.
1006 """
1007 cls = self.__class__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1008 if name in cls.__class_vars__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1009 raise AttributeError( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1010 f'{name!r} is a ClassVar of `{cls.__name__}` and cannot be set on an instance. '
1011 f'If you want to set a value on the class, use `{cls.__name__}.{name} = value`.'
1012 )
1013 elif not _fields.is_valid_field_name(name): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1014 if (attribute := cls.__private_attributes__.get(name)) is not None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1015 if hasattr(attribute, '__set__'): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1016 return lambda model, _name, val: attribute.__set__(model, val) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1017 else:
1018 return _SIMPLE_SETATTR_HANDLERS['private'] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1019 else:
1020 _object_setattr(self, name, value) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1021 return None # Can not return memoized handler with possibly freeform attr names 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1023 attr = getattr(cls, name, None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1024 # NOTE: We currently special case properties and `cached_property`, but we might need
1025 # to generalize this to all data/non-data descriptors at some point. For non-data descriptors
1026 # (such as `cached_property`), it isn't obvious though. `cached_property` caches the value
1027 # to the instance's `__dict__`, but other non-data descriptors might do things differently.
1028 if isinstance(attr, cached_property): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1029 return _SIMPLE_SETATTR_HANDLERS['cached_property'] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1031 _check_frozen(cls, name, value) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1033 # We allow properties to be set only on non frozen models for now (to match dataclasses).
1034 # This can be changed if it ever gets requested.
1035 if isinstance(attr, property): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1036 return lambda model, _name, val: attr.__set__(model, val) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1037 elif cls.model_config.get('validate_assignment'): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1038 return _SIMPLE_SETATTR_HANDLERS['validate_assignment'] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1039 elif name not in cls.__pydantic_fields__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1040 if cls.model_config.get('extra') != 'allow': 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1041 # TODO - matching error
1042 raise ValueError(f'"{cls.__name__}" object has no field "{name}"') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1043 elif attr is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1044 # attribute does not exist, so put it in extra
1045 self.__pydantic_extra__[name] = value 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1046 return None # Can not return memoized handler with possibly freeform attr names 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1047 else:
1048 # attribute _does_ exist, and was not in extra, so update it
1049 return _SIMPLE_SETATTR_HANDLERS['extra_known'] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1050 else:
1051 return _SIMPLE_SETATTR_HANDLERS['model_field'] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1053 def __delattr__(self, item: str) -> Any: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1054 cls = self.__class__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1056 if item in self.__private_attributes__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1057 attribute = self.__private_attributes__[item] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1058 if hasattr(attribute, '__delete__'): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1059 attribute.__delete__(self) # type: ignore 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1060 return 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1062 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1063 # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
1064 del self.__pydantic_private__[item] # type: ignore 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1065 return 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1066 except KeyError as exc: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1067 raise AttributeError(f'{cls.__name__!r} object has no attribute {item!r}') from exc 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1069 # Allow cached properties to be deleted (even if the class is frozen):
1070 attr = getattr(cls, item, None) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1071 if isinstance(attr, cached_property): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1072 return object.__delattr__(self, item) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1074 _check_frozen(cls, name=item, value=None) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1076 if item in self.__pydantic_fields__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1077 object.__delattr__(self, item) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1078 elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1079 del self.__pydantic_extra__[item] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1080 else:
1081 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1082 object.__delattr__(self, item) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1083 except AttributeError: 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1084 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1086 # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
1087 # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
1088 def __replace__(self, **changes: Any) -> Self: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1089 return self.model_copy(update=changes) 1adefghbjk
1091 def __getstate__(self) -> dict[Any, Any]: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1092 private = self.__pydantic_private__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1093 if private: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1094 private = {k: v for k, v in private.items() if v is not PydanticUndefined} 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1095 return { 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1096 '__dict__': self.__dict__,
1097 '__pydantic_extra__': self.__pydantic_extra__,
1098 '__pydantic_fields_set__': self.__pydantic_fields_set__,
1099 '__pydantic_private__': private,
1100 }
1102 def __setstate__(self, state: dict[Any, Any]) -> None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1103 _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {})) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1104 _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {})) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1105 _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {})) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1106 _object_setattr(self, '__dict__', state.get('__dict__', {})) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1108 if not TYPE_CHECKING: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1110 def __eq__(self, other: Any) -> bool: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1111 if isinstance(other, BaseModel): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1112 # When comparing instances of generic types for equality, as long as all field values are equal,
1113 # only require their generic origin types to be equal, rather than exact type equality.
1114 # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
1115 self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1116 other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1118 # Perform common checks first
1119 if not ( 1CDFr
1120 self_type == other_type
1121 and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None)
1122 and self.__pydantic_extra__ == other.__pydantic_extra__
1123 ):
1124 return False 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1126 # We only want to compare pydantic fields but ignoring fields is costly.
1127 # We'll perform a fast check first, and fallback only when needed
1128 # See GH-7444 and GH-7825 for rationale and a performance benchmark
1130 # First, do the fast (and sometimes faulty) __dict__ comparison
1131 if self.__dict__ == other.__dict__: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1132 # If the check above passes, then pydantic fields are equal, we can return early
1133 return True 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1135 # We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return
1136 # early if there are no keys to ignore (we would just return False later on anyway)
1137 model_fields = type(self).__pydantic_fields__.keys() 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1138 if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1139 return False 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1141 # If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore
1142 # Resort to costly filtering of the __dict__ objects
1143 # We use operator.itemgetter because it is much faster than dict comprehensions
1144 # NOTE: Contrary to standard python class and instances, when the Model class has a default value for an
1145 # attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute
1146 # raises an error in BaseModel.__getattr__ instead of returning the class attribute
1147 # So we can use operator.itemgetter() instead of operator.attrgetter()
1148 getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1149 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1150 return getter(self.__dict__) == getter(other.__dict__) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1151 except KeyError:
1152 # In rare cases (such as when using the deprecated BaseModel.copy() method),
1153 # the __dict__ may not contain all model fields, which is how we can get here.
1154 # getter(self.__dict__) is much faster than any 'safe' method that accounts
1155 # for missing keys, and wrapping it in a `try` doesn't slow things down much
1156 # in the common case.
1157 self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__)
1158 other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__)
1159 return getter(self_fields_proxy) == getter(other_fields_proxy)
1161 # other instance is not a BaseModel
1162 else:
1163 return NotImplemented # delegate to the other item in the comparison 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1165 if TYPE_CHECKING: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1166 # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits
1167 # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of
1168 # subclass initialization.
1170 def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
1171 """This signature is included purely to help type-checkers check arguments to class declaration, which
1172 provides a way to conveniently set model_config key/value pairs.
1174 ```python
1175 from pydantic import BaseModel
1177 class MyModel(BaseModel, extra='allow'): ...
1178 ```
1180 However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
1181 of the config arguments, and will only receive any keyword arguments passed during class initialization
1182 that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)
1184 Args:
1185 **kwargs: Keyword arguments passed to the class definition, which set model_config
1187 Note:
1188 You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
1189 *after* the class is fully initialized.
1190 """
1192 def __iter__(self) -> TupleGenerator: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1193 """So `dict(model)` works."""
1194 yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1195 extra = self.__pydantic_extra__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1196 if extra: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1197 yield from extra.items() 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1199 def __repr__(self) -> str: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1200 return f'{self.__repr_name__()}({self.__repr_str__(", ")})' 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1202 def __repr_args__(self) -> _repr.ReprArgs: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1203 # Eagerly create the repr of computed fields, as this may trigger access of cached properties and as such
1204 # modify the instance's `__dict__`. If we don't do it now, it could happen when iterating over the `__dict__`
1205 # below if the instance happens to be referenced in a field, and would modify the `__dict__` size *during* iteration.
1206 computed_fields_repr_args = [ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1207 (k, getattr(self, k)) for k, v in self.__pydantic_computed_fields__.items() if v.repr
1208 ]
1210 for k, v in self.__dict__.items(): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1211 field = self.__pydantic_fields__.get(k) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1212 if field and field.repr: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1213 if v is not self: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1214 yield k, v 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1215 else:
1216 yield k, self.__repr_recursion__(v) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1217 # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
1218 # This can happen if a `ValidationError` is raised during initialization and the instance's
1219 # repr is generated as part of the exception handling. Therefore, we use `getattr` here
1220 # with a fallback, even though the type hints indicate the attribute will always be present.
1221 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1222 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1223 except AttributeError: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1224 pydantic_extra = None 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1226 if pydantic_extra is not None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1227 yield from ((k, v) for k, v in pydantic_extra.items()) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1228 yield from computed_fields_repr_args 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1230 # take logic from `_repr.Representation` without the side effects of inheritance, see #5740
1231 __repr_name__ = _repr.Representation.__repr_name__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1232 __repr_recursion__ = _repr.Representation.__repr_recursion__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1233 __repr_str__ = _repr.Representation.__repr_str__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1234 __pretty__ = _repr.Representation.__pretty__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1235 __rich_repr__ = _repr.Representation.__rich_repr__ 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1237 def __str__(self) -> str: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1238 return self.__repr_str__(' ') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1240 # ##### Deprecated methods from v1 #####
1241 @property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1242 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1243 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=None
1244 )
1245 def __fields__(self) -> dict[str, FieldInfo]: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1246 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1247 'The `__fields__` attribute is deprecated, use `model_fields` instead.',
1248 category=PydanticDeprecatedSince20,
1249 stacklevel=2,
1250 )
1251 return getattr(type(self), '__pydantic_fields__', {}) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1253 @property 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1254 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1255 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
1256 category=None,
1257 )
1258 def __fields_set__(self) -> set[str]: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1259 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1260 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
1261 category=PydanticDeprecatedSince20,
1262 stacklevel=2,
1263 )
1264 return self.__pydantic_fields_set__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1266 @typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1267 def dict( # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1268 self,
1269 *,
1270 include: IncEx | None = None,
1271 exclude: IncEx | None = None,
1272 by_alias: bool = False,
1273 exclude_unset: bool = False,
1274 exclude_defaults: bool = False,
1275 exclude_none: bool = False,
1276 ) -> Dict[str, Any]: # noqa UP006
1277 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1278 'The `dict` method is deprecated; use `model_dump` instead.',
1279 category=PydanticDeprecatedSince20,
1280 stacklevel=2,
1281 )
1282 return self.model_dump( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1283 include=include,
1284 exclude=exclude,
1285 by_alias=by_alias,
1286 exclude_unset=exclude_unset,
1287 exclude_defaults=exclude_defaults,
1288 exclude_none=exclude_none,
1289 )
1291 @typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1292 def json( # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1293 self,
1294 *,
1295 include: IncEx | None = None,
1296 exclude: IncEx | None = None,
1297 by_alias: bool = False,
1298 exclude_unset: bool = False,
1299 exclude_defaults: bool = False,
1300 exclude_none: bool = False,
1301 encoder: Callable[[Any], Any] | None = PydanticUndefined, # type: ignore[assignment]
1302 models_as_dict: bool = PydanticUndefined, # type: ignore[assignment]
1303 **dumps_kwargs: Any,
1304 ) -> str:
1305 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1306 'The `json` method is deprecated; use `model_dump_json` instead.',
1307 category=PydanticDeprecatedSince20,
1308 stacklevel=2,
1309 )
1310 if encoder is not PydanticUndefined: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1311 raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1312 if models_as_dict is not PydanticUndefined: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1313 raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1314 if dumps_kwargs: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1315 raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.') 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1316 return self.model_dump_json( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1317 include=include,
1318 exclude=exclude,
1319 by_alias=by_alias,
1320 exclude_unset=exclude_unset,
1321 exclude_defaults=exclude_defaults,
1322 exclude_none=exclude_none,
1323 )
1325 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1326 @typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1327 def parse_obj(cls, obj: Any) -> Self: # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1328 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1329 'The `parse_obj` method is deprecated; use `model_validate` instead.',
1330 category=PydanticDeprecatedSince20,
1331 stacklevel=2,
1332 )
1333 return cls.model_validate(obj) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1335 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1336 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1337 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1338 'otherwise load the data then use `model_validate` instead.',
1339 category=None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1340 )
1341 def parse_raw( # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1342 cls,
1343 b: str | bytes, 1cladeFrmnfghJiobjk
1344 *,
1345 content_type: str | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1346 encoding: str = 'utf8', 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1347 proto: DeprecatedParseProtocol | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1348 allow_pickle: bool = False, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1349 ) -> Self: # pragma: no cover 1cladeFrmnfghJiobjk
1350 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1351 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1352 'otherwise load the data then use `model_validate` instead.',
1353 category=PydanticDeprecatedSince20, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1354 stacklevel=2, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1355 )
1356 from .deprecated import parse 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1358 try: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1359 obj = parse.load_str_bytes( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1360 b, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1361 proto=proto, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1362 content_type=content_type, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1363 encoding=encoding, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1364 allow_pickle=allow_pickle, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1365 )
1366 except (ValueError, TypeError) as exc: 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1367 import json 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1369 # try to match V1
1370 if isinstance(exc, UnicodeDecodeError): 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1371 type_str = 'value_error.unicodedecode'
1372 elif isinstance(exc, json.JSONDecodeError): 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1373 type_str = 'value_error.jsondecode' 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1374 elif isinstance(exc, ValueError):
1375 type_str = 'value_error'
1376 else:
1377 type_str = 'type_error'
1379 # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same
1380 error: pydantic_core.InitErrorDetails = { 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1381 # The type: ignore on the next line is to ignore the requirement of LiteralString
1382 'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1383 'loc': ('__root__',), 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1384 'input': b, 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1385 }
1386 raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error]) 1CDpuqvcladeGHwxyzmnfghEIsAtBiobjk
1387 return cls.model_validate(obj) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1389 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1390 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1391 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
1392 'use `model_validate_json`, otherwise `model_validate` instead.',
1393 category=None,
1394 )
1395 def parse_file( # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1396 cls,
1397 path: str | Path,
1398 *,
1399 content_type: str | None = None,
1400 encoding: str = 'utf8',
1401 proto: DeprecatedParseProtocol | None = None,
1402 allow_pickle: bool = False,
1403 ) -> Self:
1404 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1405 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
1406 'use `model_validate_json`, otherwise `model_validate` instead.',
1407 category=PydanticDeprecatedSince20,
1408 stacklevel=2,
1409 )
1410 from .deprecated import parse 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1412 obj = parse.load_file( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1413 path,
1414 proto=proto,
1415 content_type=content_type,
1416 encoding=encoding,
1417 allow_pickle=allow_pickle,
1418 )
1419 return cls.parse_obj(obj) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1421 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1422 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1423 'The `from_orm` method is deprecated; set '
1424 "`model_config['from_attributes']=True` and use `model_validate` instead.",
1425 category=None,
1426 )
1427 def from_orm(cls, obj: Any) -> Self: # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1428 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1429 'The `from_orm` method is deprecated; set '
1430 "`model_config['from_attributes']=True` and use `model_validate` instead.",
1431 category=PydanticDeprecatedSince20,
1432 stacklevel=2,
1433 )
1434 if not cls.model_config.get('from_attributes', None): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1435 raise PydanticUserError( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1436 'You must set the config attribute `from_attributes=True` to use from_orm', code=None
1437 )
1438 return cls.model_validate(obj) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1440 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1441 @typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1442 def construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1443 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1444 'The `construct` method is deprecated; use `model_construct` instead.',
1445 category=PydanticDeprecatedSince20,
1446 stacklevel=2,
1447 )
1448 return cls.model_construct(_fields_set=_fields_set, **values) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1450 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1451 'The `copy` method is deprecated; use `model_copy` instead. ' 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1452 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
1453 category=None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1454 )
1455 def copy( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1456 self,
1457 *,
1458 include: AbstractSetIntStr | MappingIntStrAny | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1459 exclude: AbstractSetIntStr | MappingIntStrAny | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1460 update: Dict[str, Any] | None = None, # noqa UP006 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1461 deep: bool = False, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1462 ) -> Self: # pragma: no cover 1cladeFrmnfghJiobjk
1463 """Returns a copy of the model.
1465 !!! warning "Deprecated"
1466 This method is now deprecated; use `model_copy` instead.
1468 If you need `include` or `exclude`, use:
1470 ```python {test="skip" lint="skip"}
1471 data = self.model_dump(include=include, exclude=exclude, round_trip=True)
1472 data = {**data, **(update or {})}
1473 copied = self.model_validate(data)
1474 ```
1476 Args:
1477 include: Optional set or mapping specifying which fields to include in the copied model.
1478 exclude: Optional set or mapping specifying which fields to exclude in the copied model.
1479 update: Optional dictionary of field-value pairs to override field values in the copied model.
1480 deep: If True, the values of fields that are Pydantic models will be deep-copied.
1482 Returns:
1483 A copy of the model with included, excluded and updated fields as specified.
1484 """
1485 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1486 'The `copy` method is deprecated; use `model_copy` instead. ' 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1487 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
1488 category=PydanticDeprecatedSince20, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1489 stacklevel=2, 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1490 )
1491 from .deprecated import copy_internals 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1493 values = dict( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1494 copy_internals._iter( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1495 self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1496 ),
1497 **(update or {}), 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1498 )
1499 if self.__pydantic_private__ is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1500 private = None 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1501 else:
1502 private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined} 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1504 if self.__pydantic_extra__ is None: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1505 extra: dict[str, Any] | None = None 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1506 else:
1507 extra = self.__pydantic_extra__.copy() 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1508 for k in list(self.__pydantic_extra__): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1509 if k not in values: # k was in the exclude 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1510 extra.pop(k)
1511 for k in list(values): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1512 if k in self.__pydantic_extra__: # k must have come from extra 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1513 extra[k] = values.pop(k) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1515 # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
1516 if update: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1517 fields_set = self.__pydantic_fields_set__ | update.keys() 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1518 else:
1519 fields_set = set(self.__pydantic_fields_set__) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1521 # removing excluded fields from `__pydantic_fields_set__`
1522 if exclude: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1523 fields_set -= set(exclude) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1525 return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1527 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1528 @typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1529 def schema( # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1530 cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE
1531 ) -> Dict[str, Any]: # noqa UP006
1532 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1533 'The `schema` method is deprecated; use `model_json_schema` instead.',
1534 category=PydanticDeprecatedSince20,
1535 stacklevel=2,
1536 )
1537 return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1539 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1540 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1541 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1542 category=None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1543 )
1544 def schema_json( # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1545 cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1546 ) -> str: # pragma: no cover 1cladeFrmnfghJiobjk
1547 warnings.warn(
1548 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
1549 category=PydanticDeprecatedSince20,
1550 stacklevel=2,
1551 )
1552 import json
1554 from .deprecated.json import pydantic_encoder
1556 return json.dumps(
1557 cls.model_json_schema(by_alias=by_alias, ref_template=ref_template),
1558 default=pydantic_encoder,
1559 **dumps_kwargs,
1560 )
1562 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1563 @typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1564 def validate(cls, value: Any) -> Self: # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1565 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1566 'The `validate` method is deprecated; use `model_validate` instead.',
1567 category=PydanticDeprecatedSince20,
1568 stacklevel=2,
1569 )
1570 return cls.model_validate(value) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1572 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1573 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1574 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
1575 category=None,
1576 )
1577 def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1578 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1579 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
1580 category=PydanticDeprecatedSince20,
1581 stacklevel=2,
1582 )
1583 if localns: # pragma: no cover 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1584 raise TypeError('`localns` arguments are not longer accepted.')
1585 cls.model_rebuild(force=True) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1587 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1588 'The private method `_iter` will be removed and should no longer be used.', category=None
1589 )
1590 def _iter(self, *args: Any, **kwargs: Any) -> Any: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1591 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1592 'The private method `_iter` will be removed and should no longer be used.',
1593 category=PydanticDeprecatedSince20,
1594 stacklevel=2,
1595 )
1596 from .deprecated import copy_internals 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1598 return copy_internals._iter(self, *args, **kwargs) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1600 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1601 'The private method `_copy_and_set_values` will be removed and should no longer be used.',
1602 category=None,
1603 )
1604 def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1605 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1606 'The private method `_copy_and_set_values` will be removed and should no longer be used.',
1607 category=PydanticDeprecatedSince20,
1608 stacklevel=2,
1609 )
1610 from .deprecated import copy_internals 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1612 return copy_internals._copy_and_set_values(self, *args, **kwargs) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1614 @classmethod 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1615 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1616 'The private method `_get_value` will be removed and should no longer be used.',
1617 category=None,
1618 )
1619 def _get_value(cls, *args: Any, **kwargs: Any) -> Any: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1620 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1621 'The private method `_get_value` will be removed and should no longer be used.',
1622 category=PydanticDeprecatedSince20,
1623 stacklevel=2,
1624 )
1625 from .deprecated import copy_internals 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1627 return copy_internals._get_value(cls, *args, **kwargs) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1629 @typing_extensions.deprecated( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1630 'The private method `_calculate_keys` will be removed and should no longer be used.',
1631 category=None,
1632 )
1633 def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1634 warnings.warn( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1635 'The private method `_calculate_keys` will be removed and should no longer be used.',
1636 category=PydanticDeprecatedSince20,
1637 stacklevel=2,
1638 )
1639 from .deprecated import copy_internals 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1641 return copy_internals._calculate_keys(self, *args, **kwargs) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1644ModelT = TypeVar('ModelT', bound=BaseModel) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1647@overload 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1648def create_model( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1649 model_name: str, 1cladeFrmnfghJiobjk
1650 /,
1651 *,
1652 __config__: ConfigDict | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1653 __doc__: str | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1654 __base__: None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1655 __module__: str = __name__, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1656 __validators__: dict[str, Callable[..., Any]] | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1657 __cls_kwargs__: dict[str, Any] | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1658 **field_definitions: Any | tuple[str, Any], 1cladeFrmnfghJiobjk
1659) -> type[BaseModel]: ... 1cladeFrmnfghJiobjk
1662@overload 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1663def create_model( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1664 model_name: str, 1cladeFrmnfghJiobjk
1665 /,
1666 *,
1667 __config__: ConfigDict | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1668 __doc__: str | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1669 __base__: type[ModelT] | tuple[type[ModelT], ...], 1cladeFrmnfghJiobjk
1670 __module__: str = __name__, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1671 __validators__: dict[str, Callable[..., Any]] | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1672 __cls_kwargs__: dict[str, Any] | None = None, 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1673 **field_definitions: Any | tuple[str, Any], 1cladeFrmnfghJiobjk
1674) -> type[ModelT]: ... 1cladeFrmnfghJiobjk
1677def create_model( # noqa: C901 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1678 model_name: str,
1679 /,
1680 *,
1681 __config__: ConfigDict | None = None,
1682 __doc__: str | None = None,
1683 __base__: type[ModelT] | tuple[type[ModelT], ...] | None = None,
1684 __module__: str | None = None,
1685 __validators__: dict[str, Callable[..., Any]] | None = None,
1686 __cls_kwargs__: dict[str, Any] | None = None,
1687 # TODO PEP 747: replace `Any` by the TypeForm:
1688 **field_definitions: Any | tuple[str, Any],
1689) -> type[ModelT]:
1690 """!!! abstract "Usage Documentation"
1691 [Dynamic Model Creation](../concepts/models.md#dynamic-model-creation)
1693 Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a
1694 subclass of [`BaseModel`][pydantic.BaseModel].
1696 Args:
1697 model_name: The name of the newly created model.
1698 __config__: The configuration of the new model.
1699 __doc__: The docstring of the new model.
1700 __base__: The base class or classes for the new model.
1701 __module__: The name of the module that the model belongs to;
1702 if `None`, the value is taken from `sys._getframe(1)`
1703 __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to
1704 be added to the model, and the values are the validation methods themselves. You can read more about functional
1705 validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators).
1706 __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`.
1707 **field_definitions: Field definitions of the new model. Either:
1709 - a single element, representing the type annotation of the field.
1710 - a two-tuple, the first element being the type and the second element the assigned value
1711 (either a default or the [`Field()`][pydantic.Field] function).
1713 Returns:
1714 The new [model][pydantic.BaseModel].
1716 Raises:
1717 PydanticUserError: If `__base__` and `__config__` are both passed.
1718 """
1719 if __base__ is None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1720 __base__ = (cast('type[ModelT]', BaseModel),) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1721 elif not isinstance(__base__, tuple): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1722 __base__ = (__base__,) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1724 __cls_kwargs__ = __cls_kwargs__ or {} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1726 fields: dict[str, Any] = {} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1727 annotations: dict[str, Any] = {} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1729 for f_name, f_def in field_definitions.items(): 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1730 if isinstance(f_def, tuple): 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1731 if len(f_def) != 2: 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1732 raise PydanticUserError( 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1733 f'Field definition for {f_name!r} should a single element representing the type or a two-tuple, the first element '
1734 'being the type and the second element the assigned value (either a default or the `Field()` function).',
1735 code='create-model-field-definitions',
1736 )
1738 annotations[f_name] = f_def[0] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1739 fields[f_name] = f_def[1] 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1740 else:
1741 annotations[f_name] = f_def 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1743 if __module__ is None: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1744 f = sys._getframe(1) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1745 __module__ = f.f_globals['__name__'] 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1747 namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__} 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1748 if __doc__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1749 namespace.update({'__doc__': __doc__}) 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1750 if __validators__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1751 namespace.update(__validators__) 1CpqcaEstib
1752 namespace.update(fields) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1753 if __config__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1754 namespace['model_config'] = __config__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1755 resolved_bases = types.resolve_bases(__base__) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1756 meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1757 if resolved_bases is not __base__: 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1758 ns['__orig_bases__'] = __base__ 1CDpuqvcladeFrGHwxyzmnfghEIsAtBiobjk
1759 namespace.update(ns) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1761 return meta( 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk
1762 model_name,
1763 resolved_bases,
1764 namespace,
1765 __pydantic_reset_parent_namespace__=False,
1766 _create_model_module=__module__,
1767 **kwds,
1768 )
1771__getattr__ = getattr_migration(__name__) 1CDpuqvcladeFrGHwxyzmnfghJEIsAtBiobjk