Coverage for pydantic/main.py: 98.10%
547 statements
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-26 11:49 +0000
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-26 11:49 +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 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
9import operator 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
10import sys 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
11import types 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
12import typing 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
13import warnings 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
14from collections.abc import Generator, Mapping 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
15from copy import copy, deepcopy 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
16from functools import cached_property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
17from typing import ( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
31import typing_extensions 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
32from pydantic_core import PydanticUndefined, ValidationError 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
33from typing_extensions import Self, TypeAlias, Unpack 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
35from . import PydanticDeprecatedSince20, PydanticDeprecatedSince211 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
36from ._internal import ( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
50from .aliases import AliasChoices, AliasPath 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
51from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
52from .config import ConfigDict 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
53from .errors import PydanticUndefinedAnnotation, PydanticUserError 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
54from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
55from .plugin._schema_validator import PluggableSchemaValidator 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
57if TYPE_CHECKING: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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 1x
67else:
68 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
69 # and https://youtrack.jetbrains.com/issue/PY-51428
70 DeprecationWarning = PydanticDeprecatedSince20 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
72__all__ = 'BaseModel', 'create_model' 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
74# Keep these type aliases available at runtime:
75TupleGenerator: TypeAlias = Generator[tuple[str, Any], None, None] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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]]] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
81_object_setattr = _model_construction.object_setattr 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
84def _check_frozen(model_cls: type[BaseModel], name: str, value: Any) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
85 if model_cls.model_config.get('frozen'): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
86 error_type = 'frozen_instance' 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
87 elif getattr(model_cls.__pydantic_fields__.get(name), 'frozen', False): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
88 error_type = 'frozen_field' 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
89 else:
90 return 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
92 raise ValidationError.from_exception_data( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
93 model_cls.__name__, [{'type': error_type, 'loc': (name,), 'input': value}]
94 )
97def _model_field_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
98 model.__dict__[name] = val 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
99 model.__pydantic_fields_set__.add(name) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
102def _private_setattr_handler(model: BaseModel, name: str, val: Any) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
103 if getattr(model, '__pydantic_private__', None) is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
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__', {}) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
109 model.__pydantic_private__[name] = val # pyright: ignore[reportOptionalSubscript] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
112_SIMPLE_SETATTR_HANDLERS: Mapping[str, Callable[[BaseModel, str, Any], None]] = { 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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() 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
157 """ 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
158 Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict].
159 """
161 __class_vars__: ClassVar[set[str]] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
162 """The names of the class variables defined on the model.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
164 __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]] # noqa: UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
165 """Metadata about the private attributes of the model.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
167 __signature__: ClassVar[Signature] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
168 """The synthesized `__init__` [`Signature`][inspect.Signature] of the model.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
170 __pydantic_complete__: ClassVar[bool] = False 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
171 """Whether model building is completed, or if there are still undefined fields.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
173 __pydantic_core_schema__: ClassVar[CoreSchema] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
174 """The core schema of the model.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
176 __pydantic_custom_init__: ClassVar[bool] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
177 """Whether the model has a custom `__init__` method.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
179 # Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation.
180 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos() 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
181 """Metadata containing the decorators defined on the model. 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
182 This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1."""
184 __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
185 """Metadata for generic models; contains data used for a similar purpose to 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
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 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
189 """Parent namespace of the model, used for automatic rebuilding of models.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
191 __pydantic_post_init__: ClassVar[None | Literal['model_post_init']] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
192 """The name of the post-init method for the model, if defined.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
194 __pydantic_root_model__: ClassVar[bool] = False 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
195 """Whether the model is a [`RootModel`][pydantic.root_model.RootModel].""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
197 __pydantic_serializer__: ClassVar[SchemaSerializer] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
198 """The `pydantic-core` `SchemaSerializer` used to dump instances of the model.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
200 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
201 """The `pydantic-core` `SchemaValidator` used to validate instances of the model.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
203 __pydantic_fields__: ClassVar[Dict[str, FieldInfo]] # noqa: UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
204 """A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects. 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
205 This replaces `Model.__fields__` from Pydantic V1.
206 """
208 __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]] # noqa: UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
209 """`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
211 __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] # noqa: UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
212 """A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
214 __pydantic_extra__: Dict[str, Any] | None = _model_construction.NoInitField(init=False) # noqa: UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
215 """A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
217 __pydantic_fields_set__: set[str] = _model_construction.NoInitField(init=False) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
218 """The names of fields explicitly set during instantiation.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
220 __pydantic_private__: Dict[str, Any] | None = _model_construction.NoInitField(init=False) # noqa: UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
221 """Values of private attributes set on the model instance.""" 1vAwBciadmopxCDEFjkefqrsPyGzHglbhntu
223 if not TYPE_CHECKING: 223 ↛ 241line 223 didn't jump to line 241 because the condition on line 223 was always true1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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__' 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
243 def __init__(self, /, **data: Any) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
253 validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
254 if self is not validated_self: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
255 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
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] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
265 @_utils.deprecated_instance_property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
266 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
267 def model_fields(cls) -> dict[str, FieldInfo]: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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__', {}) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
276 @_utils.deprecated_instance_property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
277 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
278 def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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__', {}) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
287 @property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
288 def model_extra(self) -> dict[str, Any] | None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
296 @property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
297 def model_fields_set(self) -> set[str]: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
306 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
307 def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: C901 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
330 fields_values: dict[str, Any] = {} 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
331 fields_set = set() 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
333 for name, field in cls.__pydantic_fields__.items(): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
334 if field.alias is not None and field.alias in values: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
335 fields_values[name] = values.pop(field.alias) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
336 fields_set.add(name) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
338 if (name not in fields_set) and (field.validation_alias is not None): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
339 validation_aliases: list[str | AliasPath] = ( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
340 field.validation_alias.choices
341 if isinstance(field.validation_alias, AliasChoices)
342 else [field.validation_alias]
343 )
345 for alias in validation_aliases: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
346 if isinstance(alias, str) and alias in values: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
347 fields_values[name] = values.pop(alias) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
348 fields_set.add(name) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
349 break 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
350 elif isinstance(alias, AliasPath): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
351 value = alias.search_dict_for_path(values) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
352 if value is not PydanticUndefined: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
353 fields_values[name] = value 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
354 fields_set.add(name) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
355 break 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
357 if name not in fields_set: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
358 if name in values: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
359 fields_values[name] = values.pop(name) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
360 fields_set.add(name) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
361 elif not field.is_required(): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
362 fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
363 if _fields_set is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
364 _fields_set = fields_set 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
366 _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
367 _object_setattr(m, '__dict__', fields_values) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
368 _object_setattr(m, '__pydantic_fields_set__', _fields_set) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
369 if not cls.__pydantic_root_model__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
370 _object_setattr(m, '__pydantic_extra__', _extra) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
372 if cls.__pydantic_post_init__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
373 m.model_post_init(None) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
374 # update private attributes with values set
375 if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
376 for k, v in values.items(): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
377 if k in m.__private_attributes__: 377 ↛ 376line 377 didn't jump to line 376 because the condition on line 377 was always true1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
378 m.__pydantic_private__[k] = v 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
380 elif not cls.__pydantic_root_model__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
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) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
385 return m 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
387 def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
388 """!!! abstract "Usage Documentation"
389 [`model_copy`](../concepts/models.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__() 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
407 if update: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
408 if self.model_config.get('extra') == 'allow': 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
409 for k, v in update.items(): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
410 if k in self.__pydantic_fields__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
411 copied.__dict__[k] = v 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
412 else:
413 if copied.__pydantic_extra__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
414 copied.__pydantic_extra__ = {} 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
415 copied.__pydantic_extra__[k] = v 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
416 else:
417 copied.__dict__.update(update) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
418 copied.__pydantic_fields_set__.update(update.keys()) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
419 return copied 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
421 def model_dump( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
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#python-mode)
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( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
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( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
480 self,
481 *,
482 indent: int | None = None,
483 ensure_ascii: bool = False,
484 include: IncEx | None = None,
485 exclude: IncEx | None = None,
486 context: Any | None = None,
487 by_alias: bool | None = None,
488 exclude_unset: bool = False,
489 exclude_defaults: bool = False,
490 exclude_none: bool = False,
491 round_trip: bool = False,
492 warnings: bool | Literal['none', 'warn', 'error'] = True,
493 fallback: Callable[[Any], Any] | None = None,
494 serialize_as_any: bool = False,
495 ) -> str:
496 """!!! abstract "Usage Documentation"
497 [`model_dump_json`](../concepts/serialization.md#json-mode)
499 Generates a JSON representation of the model using Pydantic's `to_json` method.
501 Args:
502 indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
503 ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
504 If `False` (the default), these characters will be output as-is.
505 include: Field(s) to include in the JSON output.
506 exclude: Field(s) to exclude from the JSON output.
507 context: Additional context to pass to the serializer.
508 by_alias: Whether to serialize using field aliases.
509 exclude_unset: Whether to exclude fields that have not been explicitly set.
510 exclude_defaults: Whether to exclude fields that are set to their default value.
511 exclude_none: Whether to exclude fields that have a value of `None`.
512 round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
513 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
514 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
515 fallback: A function to call when an unknown value is encountered. If not provided,
516 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
517 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
519 Returns:
520 A JSON string representation of the model.
521 """
522 return self.__pydantic_serializer__.to_json( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
523 self,
524 indent=indent,
525 ensure_ascii=ensure_ascii,
526 include=include,
527 exclude=exclude,
528 context=context,
529 by_alias=by_alias,
530 exclude_unset=exclude_unset,
531 exclude_defaults=exclude_defaults,
532 exclude_none=exclude_none,
533 round_trip=round_trip,
534 warnings=warnings,
535 fallback=fallback,
536 serialize_as_any=serialize_as_any,
537 ).decode()
539 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
540 def model_json_schema( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
541 cls,
542 by_alias: bool = True,
543 ref_template: str = DEFAULT_REF_TEMPLATE,
544 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
545 mode: JsonSchemaMode = 'validation',
546 ) -> dict[str, Any]:
547 """Generates a JSON schema for a model class.
549 Args:
550 by_alias: Whether to use attribute aliases or not.
551 ref_template: The reference template.
552 schema_generator: To override the logic used to generate the JSON schema, as a subclass of
553 `GenerateJsonSchema` with your desired modifications
554 mode: The mode in which to generate the schema.
556 Returns:
557 The JSON schema for the given model class.
558 """
559 return model_json_schema( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
560 cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode
561 )
563 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
564 def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
565 """Compute the class name for parametrizations of generic classes.
567 This method can be overridden to achieve a custom naming scheme for generic BaseModels.
569 Args:
570 params: Tuple of types of the class. Given a generic class
571 `Model` with 2 type variables and a concrete model `Model[str, int]`,
572 the value `(str, int)` would be passed to `params`.
574 Returns:
575 String representing the new class where `params` are passed to `cls` as type variables.
577 Raises:
578 TypeError: Raised when trying to generate concrete names for non-generic models.
579 """
580 if not issubclass(cls, typing.Generic): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
581 raise TypeError('Concrete names should only be generated for generic models.') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
583 # Any strings received should represent forward references, so we handle them specially below.
584 # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
585 # we may be able to remove this special case.
586 param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
587 params_component = ', '.join(param_names) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
588 return f'{cls.__name__}[{params_component}]' 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
590 def model_post_init(self, context: Any, /) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
591 """Override this method to perform additional initialization after `__init__` and `model_construct`.
592 This is useful if you want to do some validation that requires the entire model to be initialized.
593 """
595 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
596 def model_rebuild( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
597 cls,
598 *,
599 force: bool = False,
600 raise_errors: bool = True,
601 _parent_namespace_depth: int = 2,
602 _types_namespace: MappingNamespace | None = None,
603 ) -> bool | None:
604 """Try to rebuild the pydantic-core schema for the model.
606 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
607 the initial attempt to build the schema, and automatic rebuilding fails.
609 Args:
610 force: Whether to force the rebuilding of the model schema, defaults to `False`.
611 raise_errors: Whether to raise errors, defaults to `True`.
612 _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
613 _types_namespace: The types namespace, defaults to `None`.
615 Returns:
616 Returns `None` if the schema is already "complete" and rebuilding was not required.
617 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
618 """
619 already_complete = cls.__pydantic_complete__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
620 if already_complete and not force: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
621 return None 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
623 cls.__pydantic_complete__ = False 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
625 for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
626 if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
627 # Deleting the validator/serializer is necessary as otherwise they can get reused in
628 # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
629 # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
630 # Same applies for the core schema that can be reused in schema generation.
631 delattr(cls, attr) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
633 if _types_namespace is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
634 rebuild_ns = _types_namespace 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
635 elif _parent_namespace_depth > 0: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
636 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
637 else:
638 rebuild_ns = {} 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
640 parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
642 ns_resolver = _namespace_utils.NsResolver( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
643 parent_namespace={**rebuild_ns, **parent_ns},
644 )
646 return _model_construction.complete_model_class( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
647 cls,
648 _config.ConfigWrapper(cls.model_config, check=False),
649 ns_resolver,
650 raise_errors=raise_errors,
651 # If the model was already complete, we don't need to call the hook again.
652 call_on_complete_hook=not already_complete,
653 )
655 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
656 def model_validate( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
657 cls,
658 obj: Any,
659 *,
660 strict: bool | None = None,
661 from_attributes: bool | None = None,
662 context: Any | None = None,
663 by_alias: bool | None = None,
664 by_name: bool | None = None,
665 ) -> Self:
666 """Validate a pydantic model instance.
668 Args:
669 obj: The object to validate.
670 strict: Whether to enforce types strictly.
671 from_attributes: Whether to extract data from object attributes.
672 context: Additional context to pass to the validator.
673 by_alias: Whether to use the field's alias when validating against the provided input data.
674 by_name: Whether to use the field's name when validating against the provided input data.
676 Raises:
677 ValidationError: If the object could not be validated.
679 Returns:
680 The validated model instance.
681 """
682 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
683 __tracebackhide__ = True 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
685 if by_alias is False and by_name is not True: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
686 raise PydanticUserError( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
687 'At least one of `by_alias` or `by_name` must be set to True.',
688 code='validate-by-alias-and-name-false',
689 )
691 return cls.__pydantic_validator__.validate_python( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
692 obj, strict=strict, from_attributes=from_attributes, context=context, by_alias=by_alias, by_name=by_name
693 )
695 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
696 def model_validate_json( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
697 cls,
698 json_data: str | bytes | bytearray,
699 *,
700 strict: bool | None = None,
701 context: Any | None = None,
702 by_alias: bool | None = None,
703 by_name: bool | None = None,
704 ) -> Self:
705 """!!! abstract "Usage Documentation"
706 [JSON Parsing](../concepts/json.md#json-parsing)
708 Validate the given JSON data against the Pydantic model.
710 Args:
711 json_data: The JSON data to validate.
712 strict: Whether to enforce types strictly.
713 context: Extra variables to pass to the validator.
714 by_alias: Whether to use the field's alias when validating against the provided input data.
715 by_name: Whether to use the field's name when validating against the provided input data.
717 Returns:
718 The validated Pydantic model.
720 Raises:
721 ValidationError: If `json_data` is not a JSON string or the object could not be validated.
722 """
723 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
724 __tracebackhide__ = True 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
726 if by_alias is False and by_name is not True: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
727 raise PydanticUserError( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
728 'At least one of `by_alias` or `by_name` must be set to True.',
729 code='validate-by-alias-and-name-false',
730 )
732 return cls.__pydantic_validator__.validate_json( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
733 json_data, strict=strict, context=context, by_alias=by_alias, by_name=by_name
734 )
736 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
737 def model_validate_strings( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
738 cls,
739 obj: Any,
740 *,
741 strict: bool | None = None,
742 context: Any | None = None,
743 by_alias: bool | None = None,
744 by_name: bool | None = None,
745 ) -> Self:
746 """Validate the given object with string data against the Pydantic model.
748 Args:
749 obj: The object containing string data to validate.
750 strict: Whether to enforce types strictly.
751 context: Extra variables to pass to the validator.
752 by_alias: Whether to use the field's alias when validating against the provided input data.
753 by_name: Whether to use the field's name when validating against the provided input data.
755 Returns:
756 The validated Pydantic model.
757 """
758 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
759 __tracebackhide__ = True 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
761 if by_alias is False and by_name is not True: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
762 raise PydanticUserError( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
763 'At least one of `by_alias` or `by_name` must be set to True.',
764 code='validate-by-alias-and-name-false',
765 )
767 return cls.__pydantic_validator__.validate_strings( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
768 obj, strict=strict, context=context, by_alias=by_alias, by_name=by_name
769 )
771 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
772 def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
773 # This warning is only emitted when calling `super().__get_pydantic_core_schema__` from a model subclass.
774 # In the generate schema logic, this method (`BaseModel.__get_pydantic_core_schema__`) is special cased to
775 # *not* be called if not overridden.
776 warnings.warn(
777 'The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated. If you are calling '
778 '`super().__get_pydantic_core_schema__` when overriding the method on a Pydantic model, consider using '
779 '`handler(source)` instead. However, note that overriding this method on models can lead to unexpected '
780 'side effects.',
781 PydanticDeprecatedSince211,
782 stacklevel=2,
783 )
784 # Logic copied over from `GenerateSchema._model_schema`:
785 schema = cls.__dict__.get('__pydantic_core_schema__')
786 if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema):
787 return cls.__pydantic_core_schema__
789 return handler(source)
791 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
792 def __get_pydantic_json_schema__( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
793 cls,
794 core_schema: CoreSchema,
795 handler: GetJsonSchemaHandler,
796 /,
797 ) -> JsonSchemaValue:
798 """Hook into generating the model's JSON schema.
800 Args:
801 core_schema: A `pydantic-core` CoreSchema.
802 You can ignore this argument and call the handler with a new CoreSchema,
803 wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
804 or just call the handler with the original schema.
805 handler: Call into Pydantic's internal JSON schema generation.
806 This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
807 generation fails.
808 Since this gets called by `BaseModel.model_json_schema` you can override the
809 `schema_generator` argument to that function to change JSON schema generation globally
810 for a type.
812 Returns:
813 A JSON schema, as a Python object.
814 """
815 return handler(core_schema) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
817 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
818 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
819 """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
820 only after basic class initialization is complete. In particular, attributes like `model_fields` will
821 be present when this is called, but forward annotations are not guaranteed to be resolved yet,
822 meaning that creating an instance of the class may fail.
824 This is necessary because `__init_subclass__` will always be called by `type.__new__`,
825 and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
826 `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
828 This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
829 any kwargs passed to the class definition that aren't used internally by Pydantic.
831 Args:
832 **kwargs: Any keyword arguments passed to the class definition that aren't used internally
833 by Pydantic.
835 Note:
836 You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
837 instead, which is called once the class and its fields are fully initialized and ready for validation.
838 """
840 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
841 def __pydantic_on_complete__(cls) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
842 """This is called once the class and its fields are fully initialized and ready to be used.
844 This typically happens when the class is created (just before
845 [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
846 except when forward annotations are used that could not immediately be resolved.
847 In that case, it will be called later, when the model is rebuilt automatically or explicitly using
848 [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
849 """
851 def __class_getitem__( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
852 cls, typevar_values: type[Any] | tuple[type[Any], ...]
853 ) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef:
854 cached = _generics.get_cached_generic_type_early(cls, typevar_values) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
855 if cached is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
856 return cached 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
858 if cls is BaseModel: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
859 raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
860 if not hasattr(cls, '__parameters__'): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
861 raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
862 if not cls.__pydantic_generic_metadata__['parameters'] and typing.Generic not in cls.__bases__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
863 raise TypeError(f'{cls} is not a generic class') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
865 if not isinstance(typevar_values, tuple): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
866 typevar_values = (typevar_values,) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
868 # For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`,
869 # this gives us `{T: str, U: bool, V: int}`:
870 typevars_map = _generics.map_generic_model_arguments(cls, typevar_values) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
871 # We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`):
872 typevar_values = tuple(v for v in typevars_map.values()) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
874 if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
875 submodel = cls # if arguments are equal to parameters it's the same object 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
876 _generics.set_cached_generic_type(cls, typevar_values, submodel) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
877 else:
878 parent_args = cls.__pydantic_generic_metadata__['args'] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
879 if not parent_args: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
880 args = typevar_values 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
881 else:
882 args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
884 origin = cls.__pydantic_generic_metadata__['origin'] or cls 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
885 model_name = origin.model_parametrized_name(args) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
886 params = tuple( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
887 {param: None for param in _generics.iter_contained_typevars(typevars_map.values())}
888 ) # use dict as ordered set
890 with _generics.generic_recursion_self_type(origin, args) as maybe_self_type: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
891 cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
892 if cached is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
893 return cached 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
895 if maybe_self_type is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
896 return maybe_self_type 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
898 # Attempt to rebuild the origin in case new types have been defined
899 try: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
900 # depth 2 gets you above this __class_getitem__ call.
901 # Note that we explicitly provide the parent ns, otherwise
902 # `model_rebuild` will use the parent ns no matter if it is the ns of a module.
903 # We don't want this here, as this has unexpected effects when a model
904 # is being parametrized during a forward annotation evaluation.
905 parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
906 origin.model_rebuild(_types_namespace=parent_ns) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
907 except PydanticUndefinedAnnotation: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
908 # It's okay if it fails, it just means there are still undefined types
909 # that could be evaluated later.
910 pass 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
912 submodel = _generics.create_generic_submodel(model_name, origin, args, params) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
914 _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
916 return submodel 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
918 def __copy__(self) -> Self: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
919 """Returns a shallow copy of the model."""
920 cls = type(self) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
921 m = cls.__new__(cls) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
922 _object_setattr(m, '__dict__', copy(self.__dict__)) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
923 _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__)) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
924 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
926 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
927 _object_setattr(m, '__pydantic_private__', None) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
928 else:
929 _object_setattr( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
930 m,
931 '__pydantic_private__',
932 {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
933 )
935 return m 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
937 def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
938 """Returns a deep copy of the model."""
939 cls = type(self) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
940 m = cls.__new__(cls) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
941 _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
942 _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo)) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
943 # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
944 # and attempting a deepcopy would be marginally slower.
945 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
947 if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
948 _object_setattr(m, '__pydantic_private__', None) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
949 else:
950 _object_setattr( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
951 m,
952 '__pydantic_private__',
953 deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
954 )
956 return m 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
958 if not TYPE_CHECKING: 958 ↛ 1094line 958 didn't jump to line 1094 because the condition on line 958 was always true1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
959 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
960 # The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643
962 def __getattr__(self, item: str) -> Any: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
963 private_attributes = object.__getattribute__(self, '__private_attributes__') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
964 if item in private_attributes: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
965 attribute = private_attributes[item] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
966 if hasattr(attribute, '__get__'): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
967 return attribute.__get__(self, type(self)) # type: ignore 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
969 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
970 # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
971 return self.__pydantic_private__[item] # type: ignore 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
972 except KeyError as exc: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
973 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
974 else:
975 # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
976 # See `BaseModel.__repr_args__` for more details
977 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
978 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
979 except AttributeError: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
980 pydantic_extra = None 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
982 if pydantic_extra: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
983 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
984 return pydantic_extra[item] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
985 except KeyError as exc: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
986 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
987 else:
988 if hasattr(self.__class__, item): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
989 return super().__getattribute__(item) # Raises AttributeError if appropriate 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
990 else:
991 # this is the current error
992 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
994 def __setattr__(self, name: str, value: Any) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
995 if (setattr_handler := self.__pydantic_setattr_handlers__.get(name)) is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
996 setattr_handler(self, name, value) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
997 # if None is returned from _setattr_handler, the attribute was set directly
998 elif (setattr_handler := self._setattr_handler(name, value)) is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
999 setattr_handler(self, name, value) # call here to not memo on possibly unknown fields 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1000 self.__pydantic_setattr_handlers__[name] = setattr_handler # memoize the handler for faster access 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1002 def _setattr_handler(self, name: str, value: Any) -> Callable[[BaseModel, str, Any], None] | None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1003 """Get a handler for setting an attribute on the model instance.
1005 Returns:
1006 A handler for setting an attribute on the model instance. Used for memoization of the handler.
1007 Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`
1008 Returns `None` when memoization is not safe, then the attribute is set directly.
1009 """
1010 cls = self.__class__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1011 if name in cls.__class_vars__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1012 raise AttributeError( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1013 f'{name!r} is a ClassVar of `{cls.__name__}` and cannot be set on an instance. '
1014 f'If you want to set a value on the class, use `{cls.__name__}.{name} = value`.'
1015 )
1016 elif not _fields.is_valid_field_name(name): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1017 if (attribute := cls.__private_attributes__.get(name)) is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1018 if hasattr(attribute, '__set__'): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1019 return lambda model, _name, val: attribute.__set__(model, val) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1020 else:
1021 return _SIMPLE_SETATTR_HANDLERS['private'] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1022 else:
1023 _object_setattr(self, name, value) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1024 return None # Can not return memoized handler with possibly freeform attr names 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1026 attr = getattr(cls, name, None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1027 # NOTE: We currently special case properties and `cached_property`, but we might need
1028 # to generalize this to all data/non-data descriptors at some point. For non-data descriptors
1029 # (such as `cached_property`), it isn't obvious though. `cached_property` caches the value
1030 # to the instance's `__dict__`, but other non-data descriptors might do things differently.
1031 if isinstance(attr, cached_property): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1032 return _SIMPLE_SETATTR_HANDLERS['cached_property'] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1034 _check_frozen(cls, name, value) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1036 # We allow properties to be set only on non frozen models for now (to match dataclasses).
1037 # This can be changed if it ever gets requested.
1038 if isinstance(attr, property): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1039 return lambda model, _name, val: attr.__set__(model, val) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1040 elif cls.model_config.get('validate_assignment'): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1041 return _SIMPLE_SETATTR_HANDLERS['validate_assignment'] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1042 elif name not in cls.__pydantic_fields__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1043 if cls.model_config.get('extra') != 'allow': 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1044 # TODO - matching error
1045 raise ValueError(f'"{cls.__name__}" object has no field "{name}"') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1046 elif attr is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1047 # attribute does not exist, so put it in extra
1048 self.__pydantic_extra__[name] = value 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1049 return None # Can not return memoized handler with possibly freeform attr names 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1050 else:
1051 # attribute _does_ exist, and was not in extra, so update it
1052 return _SIMPLE_SETATTR_HANDLERS['extra_known'] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1053 else:
1054 return _SIMPLE_SETATTR_HANDLERS['model_field'] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1056 def __delattr__(self, item: str) -> Any: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1057 cls = self.__class__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1059 if item in self.__private_attributes__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1060 attribute = self.__private_attributes__[item] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1061 if hasattr(attribute, '__delete__'): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1062 attribute.__delete__(self) # type: ignore 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1063 return 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1065 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1066 # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
1067 del self.__pydantic_private__[item] # type: ignore 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1068 return 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1069 except KeyError as exc: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1070 raise AttributeError(f'{cls.__name__!r} object has no attribute {item!r}') from exc 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1072 # Allow cached properties to be deleted (even if the class is frozen):
1073 attr = getattr(cls, item, None) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1074 if isinstance(attr, cached_property): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1075 return object.__delattr__(self, item) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1077 _check_frozen(cls, name=item, value=None) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1079 if item in self.__pydantic_fields__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1080 object.__delattr__(self, item) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1081 elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1082 del self.__pydantic_extra__[item] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1083 else:
1084 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1085 object.__delattr__(self, item) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1086 except AttributeError: 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1087 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1089 # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
1090 # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
1091 def __replace__(self, **changes: Any) -> Self: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1092 return self.model_copy(update=changes) 1admopefqrsbhntu
1094 def __getstate__(self) -> dict[Any, Any]: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1095 private = self.__pydantic_private__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1096 if private: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1097 private = {k: v for k, v in private.items() if v is not PydanticUndefined} 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1098 return { 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1099 '__dict__': self.__dict__,
1100 '__pydantic_extra__': self.__pydantic_extra__,
1101 '__pydantic_fields_set__': self.__pydantic_fields_set__,
1102 '__pydantic_private__': private,
1103 }
1105 def __setstate__(self, state: dict[Any, Any]) -> None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1106 _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {})) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1107 _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {})) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1108 _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {})) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1109 _object_setattr(self, '__dict__', state.get('__dict__', {})) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1111 if not TYPE_CHECKING: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1113 def __eq__(self, other: Any) -> bool: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1114 if isinstance(other, BaseModel): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1115 # When comparing instances of generic types for equality, as long as all field values are equal,
1116 # only require their generic origin types to be equal, rather than exact type equality.
1117 # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
1118 self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1119 other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1121 # Perform common checks first
1122 if not ( 1IJLx
1123 self_type == other_type
1124 and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None)
1125 and self.__pydantic_extra__ == other.__pydantic_extra__
1126 ):
1127 return False 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1129 # We only want to compare pydantic fields but ignoring fields is costly.
1130 # We'll perform a fast check first, and fallback only when needed
1131 # See GH-7444 and GH-7825 for rationale and a performance benchmark
1133 # First, do the fast (and sometimes faulty) __dict__ comparison
1134 if self.__dict__ == other.__dict__: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1135 # If the check above passes, then pydantic fields are equal, we can return early
1136 return True 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1138 # We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return
1139 # early if there are no keys to ignore (we would just return False later on anyway)
1140 model_fields = type(self).__pydantic_fields__.keys() 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1141 if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1142 return False 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1144 # If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore
1145 # Resort to costly filtering of the __dict__ objects
1146 # We use operator.itemgetter because it is much faster than dict comprehensions
1147 # NOTE: Contrary to standard python class and instances, when the Model class has a default value for an
1148 # attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute
1149 # raises an error in BaseModel.__getattr__ instead of returning the class attribute
1150 # So we can use operator.itemgetter() instead of operator.attrgetter()
1151 getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1152 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1153 return getter(self.__dict__) == getter(other.__dict__) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1154 except KeyError:
1155 # In rare cases (such as when using the deprecated BaseModel.copy() method),
1156 # the __dict__ may not contain all model fields, which is how we can get here.
1157 # getter(self.__dict__) is much faster than any 'safe' method that accounts
1158 # for missing keys, and wrapping it in a `try` doesn't slow things down much
1159 # in the common case.
1160 self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__)
1161 other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__)
1162 return getter(self_fields_proxy) == getter(other_fields_proxy)
1164 # other instance is not a BaseModel
1165 else:
1166 return NotImplemented # delegate to the other item in the comparison 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1168 if TYPE_CHECKING: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1169 # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits
1170 # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of
1171 # subclass initialization.
1173 def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
1174 """This signature is included purely to help type-checkers check arguments to class declaration, which
1175 provides a way to conveniently set model_config key/value pairs.
1177 ```python
1178 from pydantic import BaseModel
1180 class MyModel(BaseModel, extra='allow'): ...
1181 ```
1183 However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
1184 of the config arguments, and will only receive any keyword arguments passed during class initialization
1185 that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)
1187 Args:
1188 **kwargs: Keyword arguments passed to the class definition, which set model_config
1190 Note:
1191 You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
1192 *after* the class is fully initialized.
1193 """
1195 def __iter__(self) -> TupleGenerator: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1196 """So `dict(model)` works."""
1197 yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1198 extra = self.__pydantic_extra__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1199 if extra: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1200 yield from extra.items() 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1202 def __repr__(self) -> str: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1203 return f'{self.__repr_name__()}({self.__repr_str__(", ")})' 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1205 def __repr_args__(self) -> _repr.ReprArgs: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1206 # Eagerly create the repr of computed fields, as this may trigger access of cached properties and as such
1207 # modify the instance's `__dict__`. If we don't do it now, it could happen when iterating over the `__dict__`
1208 # below if the instance happens to be referenced in a field, and would modify the `__dict__` size *during* iteration.
1209 computed_fields_repr_args = [ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1210 (k, getattr(self, k)) for k, v in self.__pydantic_computed_fields__.items() if v.repr
1211 ]
1213 for k, v in self.__dict__.items(): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1214 field = self.__pydantic_fields__.get(k) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1215 if field and field.repr: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1216 if v is not self: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1217 yield k, v 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1218 else:
1219 yield k, self.__repr_recursion__(v) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1220 # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
1221 # This can happen if a `ValidationError` is raised during initialization and the instance's
1222 # repr is generated as part of the exception handling. Therefore, we use `getattr` here
1223 # with a fallback, even though the type hints indicate the attribute will always be present.
1224 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1225 pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1226 except AttributeError: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1227 pydantic_extra = None 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1229 if pydantic_extra is not None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1230 yield from ((k, v) for k, v in pydantic_extra.items()) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1231 yield from computed_fields_repr_args 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1233 # take logic from `_repr.Representation` without the side effects of inheritance, see #5740
1234 __repr_name__ = _repr.Representation.__repr_name__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1235 __repr_recursion__ = _repr.Representation.__repr_recursion__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1236 __repr_str__ = _repr.Representation.__repr_str__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1237 __pretty__ = _repr.Representation.__pretty__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1238 __rich_repr__ = _repr.Representation.__rich_repr__ 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1240 def __str__(self) -> str: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1241 return self.__repr_str__(' ') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1243 # ##### Deprecated methods from v1 #####
1244 @property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1245 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1246 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=None
1247 )
1248 def __fields__(self) -> dict[str, FieldInfo]: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1249 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1250 'The `__fields__` attribute is deprecated, use `model_fields` instead.',
1251 category=PydanticDeprecatedSince20,
1252 stacklevel=2,
1253 )
1254 return getattr(type(self), '__pydantic_fields__', {}) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1256 @property 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1257 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1258 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
1259 category=None,
1260 )
1261 def __fields_set__(self) -> set[str]: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1262 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1263 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
1264 category=PydanticDeprecatedSince20,
1265 stacklevel=2,
1266 )
1267 return self.__pydantic_fields_set__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1269 @typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1270 def dict( # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1271 self,
1272 *,
1273 include: IncEx | None = None,
1274 exclude: IncEx | None = None,
1275 by_alias: bool = False,
1276 exclude_unset: bool = False,
1277 exclude_defaults: bool = False,
1278 exclude_none: bool = False,
1279 ) -> Dict[str, Any]: # noqa UP006
1280 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1281 'The `dict` method is deprecated; use `model_dump` instead.',
1282 category=PydanticDeprecatedSince20,
1283 stacklevel=2,
1284 )
1285 return self.model_dump( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1286 include=include,
1287 exclude=exclude,
1288 by_alias=by_alias,
1289 exclude_unset=exclude_unset,
1290 exclude_defaults=exclude_defaults,
1291 exclude_none=exclude_none,
1292 )
1294 @typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1295 def json( # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1296 self,
1297 *,
1298 include: IncEx | None = None,
1299 exclude: IncEx | None = None,
1300 by_alias: bool = False,
1301 exclude_unset: bool = False,
1302 exclude_defaults: bool = False,
1303 exclude_none: bool = False,
1304 encoder: Callable[[Any], Any] | None = PydanticUndefined, # type: ignore[assignment]
1305 models_as_dict: bool = PydanticUndefined, # type: ignore[assignment]
1306 **dumps_kwargs: Any,
1307 ) -> str:
1308 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1309 'The `json` method is deprecated; use `model_dump_json` instead.',
1310 category=PydanticDeprecatedSince20,
1311 stacklevel=2,
1312 )
1313 if encoder is not PydanticUndefined: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1314 raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1315 if models_as_dict is not PydanticUndefined: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1316 raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1317 if dumps_kwargs: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1318 raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.') 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1319 return self.model_dump_json( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1320 include=include,
1321 exclude=exclude,
1322 by_alias=by_alias,
1323 exclude_unset=exclude_unset,
1324 exclude_defaults=exclude_defaults,
1325 exclude_none=exclude_none,
1326 )
1328 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1329 @typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1330 def parse_obj(cls, obj: Any) -> Self: # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1331 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1332 'The `parse_obj` method is deprecated; use `model_validate` instead.',
1333 category=PydanticDeprecatedSince20,
1334 stacklevel=2,
1335 )
1336 return cls.model_validate(obj) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1338 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1339 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1340 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1341 'otherwise load the data then use `model_validate` instead.',
1342 category=None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1343 )
1344 def parse_raw( # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1345 cls,
1346 b: str | bytes, 1ciadmopLxjkefqrsPglbhntu
1347 *,
1348 content_type: str | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1349 encoding: str = 'utf8', 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1350 proto: DeprecatedParseProtocol | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1351 allow_pickle: bool = False, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1352 ) -> Self: # pragma: no cover 1ciadmopLxjkefqrsPglbhntu
1353 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1354 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1355 'otherwise load the data then use `model_validate` instead.',
1356 category=PydanticDeprecatedSince20, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1357 stacklevel=2, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1358 )
1359 from .deprecated import parse 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1361 try: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1362 obj = parse.load_str_bytes( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1363 b, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1364 proto=proto, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1365 content_type=content_type, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1366 encoding=encoding, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1367 allow_pickle=allow_pickle, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1368 )
1369 except (ValueError, TypeError) as exc: 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1370 import json 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1372 # try to match V1
1373 if isinstance(exc, UnicodeDecodeError): 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1374 type_str = 'value_error.unicodedecode'
1375 elif isinstance(exc, json.JSONDecodeError): 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1376 type_str = 'value_error.jsondecode' 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1377 elif isinstance(exc, ValueError):
1378 type_str = 'value_error'
1379 else:
1380 type_str = 'type_error'
1382 # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same
1383 error: pydantic_core.InitErrorDetails = { 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1384 # The type: ignore on the next line is to ignore the requirement of LiteralString
1385 'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1386 'loc': ('__root__',), 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1387 'input': b, 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1388 }
1389 raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error]) 1IJvAwBciadmopMNCDEFjkefqrsKOyGzHglbhntu
1390 return cls.model_validate(obj) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1392 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1393 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1394 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
1395 'use `model_validate_json`, otherwise `model_validate` instead.',
1396 category=None,
1397 )
1398 def parse_file( # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1399 cls,
1400 path: str | Path,
1401 *,
1402 content_type: str | None = None,
1403 encoding: str = 'utf8',
1404 proto: DeprecatedParseProtocol | None = None,
1405 allow_pickle: bool = False,
1406 ) -> Self:
1407 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1408 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
1409 'use `model_validate_json`, otherwise `model_validate` instead.',
1410 category=PydanticDeprecatedSince20,
1411 stacklevel=2,
1412 )
1413 from .deprecated import parse 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1415 obj = parse.load_file( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1416 path,
1417 proto=proto,
1418 content_type=content_type,
1419 encoding=encoding,
1420 allow_pickle=allow_pickle,
1421 )
1422 return cls.parse_obj(obj) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1424 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1425 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1426 'The `from_orm` method is deprecated; set '
1427 "`model_config['from_attributes']=True` and use `model_validate` instead.",
1428 category=None,
1429 )
1430 def from_orm(cls, obj: Any) -> Self: # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1431 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1432 'The `from_orm` method is deprecated; set '
1433 "`model_config['from_attributes']=True` and use `model_validate` instead.",
1434 category=PydanticDeprecatedSince20,
1435 stacklevel=2,
1436 )
1437 if not cls.model_config.get('from_attributes', None): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1438 raise PydanticUserError( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1439 'You must set the config attribute `from_attributes=True` to use from_orm', code=None
1440 )
1441 return cls.model_validate(obj) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1443 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1444 @typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1445 def construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1446 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1447 'The `construct` method is deprecated; use `model_construct` instead.',
1448 category=PydanticDeprecatedSince20,
1449 stacklevel=2,
1450 )
1451 return cls.model_construct(_fields_set=_fields_set, **values) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1453 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1454 'The `copy` method is deprecated; use `model_copy` instead. ' 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1455 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
1456 category=None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1457 )
1458 def copy( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1459 self,
1460 *,
1461 include: AbstractSetIntStr | MappingIntStrAny | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1462 exclude: AbstractSetIntStr | MappingIntStrAny | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1463 update: Dict[str, Any] | None = None, # noqa UP006 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1464 deep: bool = False, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1465 ) -> Self: # pragma: no cover 1ciadmopLxjkefqrsPglbhntu
1466 """Returns a copy of the model.
1468 !!! warning "Deprecated"
1469 This method is now deprecated; use `model_copy` instead.
1471 If you need `include` or `exclude`, use:
1473 ```python {test="skip" lint="skip"}
1474 data = self.model_dump(include=include, exclude=exclude, round_trip=True)
1475 data = {**data, **(update or {})}
1476 copied = self.model_validate(data)
1477 ```
1479 Args:
1480 include: Optional set or mapping specifying which fields to include in the copied model.
1481 exclude: Optional set or mapping specifying which fields to exclude in the copied model.
1482 update: Optional dictionary of field-value pairs to override field values in the copied model.
1483 deep: If True, the values of fields that are Pydantic models will be deep-copied.
1485 Returns:
1486 A copy of the model with included, excluded and updated fields as specified.
1487 """
1488 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1489 'The `copy` method is deprecated; use `model_copy` instead. ' 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1490 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
1491 category=PydanticDeprecatedSince20, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1492 stacklevel=2, 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1493 )
1494 from .deprecated import copy_internals 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1496 values = dict( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1497 copy_internals._iter( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1498 self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1499 ),
1500 **(update or {}), 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1501 )
1502 if self.__pydantic_private__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1503 private = None 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1504 else:
1505 private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined} 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1507 if self.__pydantic_extra__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1508 extra: dict[str, Any] | None = None 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1509 else:
1510 extra = self.__pydantic_extra__.copy() 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1511 for k in list(self.__pydantic_extra__): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1512 if k not in values: # k was in the exclude 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1513 extra.pop(k)
1514 for k in list(values): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1515 if k in self.__pydantic_extra__: # k must have come from extra 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1516 extra[k] = values.pop(k) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1518 # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
1519 if update: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1520 fields_set = self.__pydantic_fields_set__ | update.keys() 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1521 else:
1522 fields_set = set(self.__pydantic_fields_set__) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1524 # removing excluded fields from `__pydantic_fields_set__`
1525 if exclude: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1526 fields_set -= set(exclude) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1528 return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1530 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1531 @typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1532 def schema( # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1533 cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE
1534 ) -> Dict[str, Any]: # noqa UP006
1535 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1536 'The `schema` method is deprecated; use `model_json_schema` instead.',
1537 category=PydanticDeprecatedSince20,
1538 stacklevel=2,
1539 )
1540 return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1542 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1543 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1544 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1545 category=None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1546 )
1547 def schema_json( # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1548 cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1549 ) -> str: # pragma: no cover 1ciadmopLxjkefqrsPglbhntu
1550 warnings.warn(
1551 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
1552 category=PydanticDeprecatedSince20,
1553 stacklevel=2,
1554 )
1555 import json
1557 from .deprecated.json import pydantic_encoder
1559 return json.dumps(
1560 cls.model_json_schema(by_alias=by_alias, ref_template=ref_template),
1561 default=pydantic_encoder,
1562 **dumps_kwargs,
1563 )
1565 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1566 @typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1567 def validate(cls, value: Any) -> Self: # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1568 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1569 'The `validate` method is deprecated; use `model_validate` instead.',
1570 category=PydanticDeprecatedSince20,
1571 stacklevel=2,
1572 )
1573 return cls.model_validate(value) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1575 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1576 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1577 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
1578 category=None,
1579 )
1580 def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1581 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1582 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
1583 category=PydanticDeprecatedSince20,
1584 stacklevel=2,
1585 )
1586 if localns: # pragma: no cover 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1587 raise TypeError('`localns` arguments are not longer accepted.')
1588 cls.model_rebuild(force=True) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1590 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1591 'The private method `_iter` will be removed and should no longer be used.', category=None
1592 )
1593 def _iter(self, *args: Any, **kwargs: Any) -> Any: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1594 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1595 'The private method `_iter` will be removed and should no longer be used.',
1596 category=PydanticDeprecatedSince20,
1597 stacklevel=2,
1598 )
1599 from .deprecated import copy_internals 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1601 return copy_internals._iter(self, *args, **kwargs) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1603 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1604 'The private method `_copy_and_set_values` will be removed and should no longer be used.',
1605 category=None,
1606 )
1607 def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1608 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1609 'The private method `_copy_and_set_values` will be removed and should no longer be used.',
1610 category=PydanticDeprecatedSince20,
1611 stacklevel=2,
1612 )
1613 from .deprecated import copy_internals 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1615 return copy_internals._copy_and_set_values(self, *args, **kwargs) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1617 @classmethod 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1618 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1619 'The private method `_get_value` will be removed and should no longer be used.',
1620 category=None,
1621 )
1622 def _get_value(cls, *args: Any, **kwargs: Any) -> Any: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1623 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1624 'The private method `_get_value` will be removed and should no longer be used.',
1625 category=PydanticDeprecatedSince20,
1626 stacklevel=2,
1627 )
1628 from .deprecated import copy_internals 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1630 return copy_internals._get_value(cls, *args, **kwargs) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1632 @typing_extensions.deprecated( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1633 'The private method `_calculate_keys` will be removed and should no longer be used.',
1634 category=None,
1635 )
1636 def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1637 warnings.warn( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1638 'The private method `_calculate_keys` will be removed and should no longer be used.',
1639 category=PydanticDeprecatedSince20,
1640 stacklevel=2,
1641 )
1642 from .deprecated import copy_internals 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1644 return copy_internals._calculate_keys(self, *args, **kwargs) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1647ModelT = TypeVar('ModelT', bound=BaseModel) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1650@overload 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1651def create_model( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1652 model_name: str, 1ciadLxjkefPglbh
1653 /,
1654 *,
1655 __config__: ConfigDict | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1656 __doc__: str | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1657 __base__: None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1658 __module__: str = __name__, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1659 __validators__: dict[str, Callable[..., Any]] | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1660 __cls_kwargs__: dict[str, Any] | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1661 **field_definitions: Any | tuple[str, Any], 1ciadLxjkefPglbh
1662) -> type[BaseModel]: ... 1ciadLxjkefPglbh
1665@overload 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1666def create_model( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1667 model_name: str, 1ciadLxjkefPglbh
1668 /,
1669 *,
1670 __config__: ConfigDict | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1671 __doc__: str | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1672 __base__: type[ModelT] | tuple[type[ModelT], ...], 1ciadLxjkefPglbh
1673 __module__: str = __name__, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1674 __validators__: dict[str, Callable[..., Any]] | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1675 __cls_kwargs__: dict[str, Any] | None = None, 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1676 **field_definitions: Any | tuple[str, Any], 1ciadLxjkefPglbh
1677) -> type[ModelT]: ... 1ciadLxjkefPglbh
1680def create_model( # noqa: C901 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1681 model_name: str,
1682 /,
1683 *,
1684 __config__: ConfigDict | None = None,
1685 __doc__: str | None = None,
1686 __base__: type[ModelT] | tuple[type[ModelT], ...] | None = None,
1687 __module__: str | None = None,
1688 __validators__: dict[str, Callable[..., Any]] | None = None,
1689 __cls_kwargs__: dict[str, Any] | None = None,
1690 # TODO PEP 747: replace `Any` by the TypeForm:
1691 **field_definitions: Any | tuple[str, Any],
1692) -> type[ModelT]:
1693 """!!! abstract "Usage Documentation"
1694 [Dynamic Model Creation](../concepts/models.md#dynamic-model-creation)
1696 Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a
1697 subclass of [`BaseModel`][pydantic.BaseModel].
1699 Args:
1700 model_name: The name of the newly created model.
1701 __config__: The configuration of the new model.
1702 __doc__: The docstring of the new model.
1703 __base__: The base class or classes for the new model.
1704 __module__: The name of the module that the model belongs to;
1705 if `None`, the value is taken from `sys._getframe(1)`
1706 __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to
1707 be added to the model, and the values are the validation methods themselves. You can read more about functional
1708 validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators).
1709 __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`.
1710 **field_definitions: Field definitions of the new model. Either:
1712 - a single element, representing the type annotation of the field.
1713 - a two-tuple, the first element being the type and the second element the assigned value
1714 (either a default or the [`Field()`][pydantic.Field] function).
1716 Returns:
1717 The new [model][pydantic.BaseModel].
1719 Raises:
1720 PydanticUserError: If `__base__` and `__config__` are both passed.
1721 """
1722 if __base__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1723 __base__ = (cast('type[ModelT]', BaseModel),) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1724 elif not isinstance(__base__, tuple): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1725 __base__ = (__base__,) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1727 __cls_kwargs__ = __cls_kwargs__ or {} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1729 fields: dict[str, Any] = {} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1730 annotations: dict[str, Any] = {} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1732 for f_name, f_def in field_definitions.items(): 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1733 if isinstance(f_def, tuple): 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1734 if len(f_def) != 2: 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1735 raise PydanticUserError( 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1736 f'Field definition for {f_name!r} should a single element representing the type or a two-tuple, the first element '
1737 'being the type and the second element the assigned value (either a default or the `Field()` function).',
1738 code='create-model-field-definitions',
1739 )
1741 annotations[f_name] = f_def[0] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1742 fields[f_name] = f_def[1] 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1743 else:
1744 annotations[f_name] = f_def 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1746 if __module__ is None: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1747 f = sys._getframe(1) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1748 __module__ = f.f_globals['__name__'] 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1750 namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__} 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1751 if __doc__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1752 namespace.update({'__doc__': __doc__}) 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1753 if __validators__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1754 namespace.update(__validators__) 1IvwcamKyzgbn
1755 namespace.update(fields) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1756 if __config__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1757 namespace['model_config'] = __config__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1758 resolved_bases = types.resolve_bases(__base__) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1759 meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1760 if resolved_bases is not __base__: 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1761 ns['__orig_bases__'] = __base__ 1IJvAwBciadmopLxMNCDEFjkefqrsKOyGzHglbhntu
1762 namespace.update(ns) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1764 return meta( 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu
1765 model_name,
1766 resolved_bases,
1767 namespace,
1768 __pydantic_reset_parent_namespace__=False,
1769 _create_model_module=__module__,
1770 **kwds,
1771 )
1774__getattr__ = getattr_migration(__name__) 1IJvAwBciadmopLxMNCDEFjkefqrsPKOyGzHglbhntu