main.py 74 KB

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