main.py 62 KB

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