main.py 83 KB

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