main.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. """Logic for creating models."""
  2. from __future__ import annotations as _annotations
  3. import types
  4. import typing
  5. import warnings
  6. from copy import copy, deepcopy
  7. from typing import Any, ClassVar
  8. import pydantic_core
  9. import typing_extensions
  10. from pydantic_core import PydanticUndefined
  11. from ._internal import (
  12. _config,
  13. _decorators,
  14. _fields,
  15. _forward_ref,
  16. _generics,
  17. _mock_val_ser,
  18. _model_construction,
  19. _repr,
  20. _typing_extra,
  21. _utils,
  22. )
  23. from ._migration import getattr_migration
  24. from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
  25. from .config import ConfigDict
  26. from .errors import PydanticUndefinedAnnotation, PydanticUserError
  27. from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr
  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 Field as _Field
  38. AnyClassMethod = classmethod[Any, Any, Any]
  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.4/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 specified during validation.
  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 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.4/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.4/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 are unset or None from the output.
  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.4/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. """Validate the given JSON data against the Pydantic model.
  442. Args:
  443. json_data: The JSON data to validate.
  444. strict: Whether to enforce types strictly.
  445. context: Extra variables to pass to the validator.
  446. Returns:
  447. The validated Pydantic model.
  448. Raises:
  449. ValueError: If `json_data` is not a JSON string.
  450. """
  451. # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
  452. __tracebackhide__ = True
  453. return cls.__pydantic_validator__.validate_json(json_data, strict=strict, context=context)
  454. @classmethod
  455. def model_validate_strings(
  456. cls: type[Model],
  457. obj: Any,
  458. *,
  459. strict: bool | None = None,
  460. context: dict[str, Any] | None = None,
  461. ) -> Model:
  462. """Validate the given object contains string data against the Pydantic model.
  463. Args:
  464. obj: The object contains string data to validate.
  465. strict: Whether to enforce types strictly.
  466. context: Extra variables to pass to the validator.
  467. Returns:
  468. The validated Pydantic model.
  469. """
  470. # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
  471. __tracebackhide__ = True
  472. return cls.__pydantic_validator__.validate_strings(obj, strict=strict, context=context)
  473. @classmethod
  474. def __get_pydantic_core_schema__(cls, __source: type[BaseModel], __handler: GetCoreSchemaHandler) -> CoreSchema:
  475. """Hook into generating the model's CoreSchema.
  476. Args:
  477. __source: The class we are generating a schema for.
  478. This will generally be the same as the `cls` argument if this is a classmethod.
  479. __handler: Call into Pydantic's internal JSON schema generation.
  480. A callable that calls into Pydantic's internal CoreSchema generation logic.
  481. Returns:
  482. A `pydantic-core` `CoreSchema`.
  483. """
  484. # Only use the cached value from this _exact_ class; we don't want one from a parent class
  485. # This is why we check `cls.__dict__` and don't use `cls.__pydantic_core_schema__` or similar.
  486. if '__pydantic_core_schema__' in cls.__dict__:
  487. # Due to the way generic classes are built, it's possible that an invalid schema may be temporarily
  488. # set on generic classes. I think we could resolve this to ensure that we get proper schema caching
  489. # for generics, but for simplicity for now, we just always rebuild if the class has a generic origin.
  490. if not cls.__pydantic_generic_metadata__['origin']:
  491. return cls.__pydantic_core_schema__
  492. return __handler(__source)
  493. @classmethod
  494. def __get_pydantic_json_schema__(
  495. cls,
  496. __core_schema: CoreSchema,
  497. __handler: GetJsonSchemaHandler,
  498. ) -> JsonSchemaValue:
  499. """Hook into generating the model's JSON schema.
  500. Args:
  501. __core_schema: A `pydantic-core` CoreSchema.
  502. You can ignore this argument and call the handler with a new CoreSchema,
  503. wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
  504. or just call the handler with the original schema.
  505. __handler: Call into Pydantic's internal JSON schema generation.
  506. This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
  507. generation fails.
  508. Since this gets called by `BaseModel.model_json_schema` you can override the
  509. `schema_generator` argument to that function to change JSON schema generation globally
  510. for a type.
  511. Returns:
  512. A JSON schema, as a Python object.
  513. """
  514. return __handler(__core_schema)
  515. @classmethod
  516. def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
  517. """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
  518. only after the class is actually fully initialized. In particular, attributes like `model_fields` will
  519. be present when this is called.
  520. This is necessary because `__init_subclass__` will always be called by `type.__new__`,
  521. and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
  522. `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
  523. This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
  524. any kwargs passed to the class definition that aren't used internally by pydantic.
  525. Args:
  526. **kwargs: Any keyword arguments passed to the class definition that aren't used internally
  527. by pydantic.
  528. """
  529. pass
  530. def __class_getitem__(
  531. cls, typevar_values: type[Any] | tuple[type[Any], ...]
  532. ) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef:
  533. cached = _generics.get_cached_generic_type_early(cls, typevar_values)
  534. if cached is not None:
  535. return cached
  536. if cls is BaseModel:
  537. raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel')
  538. if not hasattr(cls, '__parameters__'):
  539. raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic')
  540. if not cls.__pydantic_generic_metadata__['parameters'] and typing.Generic not in cls.__bases__:
  541. raise TypeError(f'{cls} is not a generic class')
  542. if not isinstance(typevar_values, tuple):
  543. typevar_values = (typevar_values,)
  544. _generics.check_parameters_count(cls, typevar_values)
  545. # Build map from generic typevars to passed params
  546. typevars_map: dict[_typing_extra.TypeVarType, type[Any]] = dict(
  547. zip(cls.__pydantic_generic_metadata__['parameters'], typevar_values)
  548. )
  549. if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map:
  550. submodel = cls # if arguments are equal to parameters it's the same object
  551. _generics.set_cached_generic_type(cls, typevar_values, submodel)
  552. else:
  553. parent_args = cls.__pydantic_generic_metadata__['args']
  554. if not parent_args:
  555. args = typevar_values
  556. else:
  557. args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args)
  558. origin = cls.__pydantic_generic_metadata__['origin'] or cls
  559. model_name = origin.model_parametrized_name(args)
  560. params = tuple(
  561. {param: None for param in _generics.iter_contained_typevars(typevars_map.values())}
  562. ) # use dict as ordered set
  563. with _generics.generic_recursion_self_type(origin, args) as maybe_self_type:
  564. if maybe_self_type is not None:
  565. return maybe_self_type
  566. cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args)
  567. if cached is not None:
  568. return cached
  569. # Attempt to rebuild the origin in case new types have been defined
  570. try:
  571. # depth 3 gets you above this __class_getitem__ call
  572. origin.model_rebuild(_parent_namespace_depth=3)
  573. except PydanticUndefinedAnnotation:
  574. # It's okay if it fails, it just means there are still undefined types
  575. # that could be evaluated later.
  576. # TODO: Make sure validation fails if there are still undefined types, perhaps using MockValidator
  577. pass
  578. submodel = _generics.create_generic_submodel(model_name, origin, args, params)
  579. # Update cache
  580. _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args)
  581. return submodel
  582. def __copy__(self: Model) -> Model:
  583. """Returns a shallow copy of the model."""
  584. cls = type(self)
  585. m = cls.__new__(cls)
  586. _object_setattr(m, '__dict__', copy(self.__dict__))
  587. _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
  588. _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
  589. if self.__pydantic_private__ is None:
  590. _object_setattr(m, '__pydantic_private__', None)
  591. else:
  592. _object_setattr(
  593. m,
  594. '__pydantic_private__',
  595. {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
  596. )
  597. return m
  598. def __deepcopy__(self: Model, memo: dict[int, Any] | None = None) -> Model:
  599. """Returns a deep copy of the model."""
  600. cls = type(self)
  601. m = cls.__new__(cls)
  602. _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
  603. _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
  604. # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
  605. # and attempting a deepcopy would be marginally slower.
  606. _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
  607. if self.__pydantic_private__ is None:
  608. _object_setattr(m, '__pydantic_private__', None)
  609. else:
  610. _object_setattr(
  611. m,
  612. '__pydantic_private__',
  613. deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
  614. )
  615. return m
  616. if not typing.TYPE_CHECKING:
  617. # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
  618. def __getattr__(self, item: str) -> Any:
  619. private_attributes = object.__getattribute__(self, '__private_attributes__')
  620. if item in private_attributes:
  621. attribute = private_attributes[item]
  622. if hasattr(attribute, '__get__'):
  623. return attribute.__get__(self, type(self)) # type: ignore
  624. try:
  625. # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
  626. return self.__pydantic_private__[item] # type: ignore
  627. except KeyError as exc:
  628. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
  629. else:
  630. # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
  631. # See `BaseModel.__repr_args__` for more details
  632. try:
  633. pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
  634. except AttributeError:
  635. pydantic_extra = None
  636. if pydantic_extra is not None:
  637. try:
  638. return pydantic_extra[item]
  639. except KeyError as exc:
  640. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
  641. else:
  642. if hasattr(self.__class__, item):
  643. return super().__getattribute__(item) # Raises AttributeError if appropriate
  644. else:
  645. # this is the current error
  646. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
  647. def __setattr__(self, name: str, value: Any) -> None:
  648. if name in self.__class_vars__:
  649. raise AttributeError(
  650. f'{name!r} is a ClassVar of `{self.__class__.__name__}` and cannot be set on an instance. '
  651. f'If you want to set a value on the class, use `{self.__class__.__name__}.{name} = value`.'
  652. )
  653. elif not _fields.is_valid_field_name(name):
  654. if self.__pydantic_private__ is None or name not in self.__private_attributes__:
  655. _object_setattr(self, name, value)
  656. else:
  657. attribute = self.__private_attributes__[name]
  658. if hasattr(attribute, '__set__'):
  659. attribute.__set__(self, value) # type: ignore
  660. else:
  661. self.__pydantic_private__[name] = value
  662. return
  663. elif self.model_config.get('frozen', None):
  664. error: pydantic_core.InitErrorDetails = {
  665. 'type': 'frozen_instance',
  666. 'loc': (name,),
  667. 'input': value,
  668. }
  669. raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error])
  670. elif getattr(self.model_fields.get(name), 'frozen', False):
  671. error: pydantic_core.InitErrorDetails = {
  672. 'type': 'frozen_field',
  673. 'loc': (name,),
  674. 'input': value,
  675. }
  676. raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error])
  677. attr = getattr(self.__class__, name, None)
  678. if isinstance(attr, property):
  679. attr.__set__(self, value)
  680. elif self.model_config.get('validate_assignment', None):
  681. self.__pydantic_validator__.validate_assignment(self, name, value)
  682. elif self.model_config.get('extra') != 'allow' and name not in self.model_fields:
  683. # TODO - matching error
  684. raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
  685. elif self.model_config.get('extra') == 'allow' and name not in self.model_fields:
  686. # SAFETY: __pydantic_extra__ is not None when extra = 'allow'
  687. self.__pydantic_extra__[name] = value # type: ignore
  688. else:
  689. self.__dict__[name] = value
  690. self.__pydantic_fields_set__.add(name)
  691. def __delattr__(self, item: str) -> Any:
  692. if item in self.__private_attributes__:
  693. attribute = self.__private_attributes__[item]
  694. if hasattr(attribute, '__delete__'):
  695. attribute.__delete__(self) # type: ignore
  696. return
  697. try:
  698. # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
  699. del self.__pydantic_private__[item] # type: ignore
  700. except KeyError as exc:
  701. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
  702. elif item in self.model_fields:
  703. object.__delattr__(self, item)
  704. elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__:
  705. del self.__pydantic_extra__[item]
  706. else:
  707. try:
  708. object.__delattr__(self, item)
  709. except AttributeError:
  710. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
  711. def __getstate__(self) -> dict[Any, Any]:
  712. private = self.__pydantic_private__
  713. if private:
  714. private = {k: v for k, v in private.items() if v is not PydanticUndefined}
  715. return {
  716. '__dict__': self.__dict__,
  717. '__pydantic_extra__': self.__pydantic_extra__,
  718. '__pydantic_fields_set__': self.__pydantic_fields_set__,
  719. '__pydantic_private__': private,
  720. }
  721. def __setstate__(self, state: dict[Any, Any]) -> None:
  722. _object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__'])
  723. _object_setattr(self, '__pydantic_extra__', state['__pydantic_extra__'])
  724. _object_setattr(self, '__pydantic_private__', state['__pydantic_private__'])
  725. _object_setattr(self, '__dict__', state['__dict__'])
  726. def __eq__(self, other: Any) -> bool:
  727. if isinstance(other, BaseModel):
  728. # When comparing instances of generic types for equality, as long as all field values are equal,
  729. # only require their generic origin types to be equal, rather than exact type equality.
  730. # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
  731. self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__
  732. other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__
  733. return (
  734. self_type == other_type
  735. and self.__dict__ == other.__dict__
  736. and self.__pydantic_private__ == other.__pydantic_private__
  737. and self.__pydantic_extra__ == other.__pydantic_extra__
  738. )
  739. else:
  740. return NotImplemented # delegate to the other item in the comparison
  741. if typing.TYPE_CHECKING:
  742. # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits
  743. # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of
  744. # subclass initialization.
  745. def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
  746. """This signature is included purely to help type-checkers check arguments to class declaration, which
  747. provides a way to conveniently set model_config key/value pairs.
  748. ```py
  749. from pydantic import BaseModel
  750. class MyModel(BaseModel, extra='allow'):
  751. ...
  752. ```
  753. However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
  754. of the config arguments, and will only receive any keyword arguments passed during class initialization
  755. that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)
  756. Args:
  757. **kwargs: Keyword arguments passed to the class definition, which set model_config
  758. Note:
  759. You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
  760. *after* the class is fully initialized.
  761. """
  762. def __iter__(self) -> TupleGenerator:
  763. """So `dict(model)` works."""
  764. yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
  765. extra = self.__pydantic_extra__
  766. if extra:
  767. yield from extra.items()
  768. def __repr__(self) -> str:
  769. return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
  770. def __repr_args__(self) -> _repr.ReprArgs:
  771. for k, v in self.__dict__.items():
  772. field = self.model_fields.get(k)
  773. if field and field.repr:
  774. yield k, v
  775. # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
  776. # This can happen if a `ValidationError` is raised during initialization and the instance's
  777. # repr is generated as part of the exception handling. Therefore, we use `getattr` here
  778. # with a fallback, even though the type hints indicate the attribute will always be present.
  779. try:
  780. pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
  781. except AttributeError:
  782. pydantic_extra = None
  783. if pydantic_extra is not None:
  784. yield from ((k, v) for k, v in pydantic_extra.items())
  785. yield from ((k, getattr(self, k)) for k, v in self.model_computed_fields.items() if v.repr)
  786. # take logic from `_repr.Representation` without the side effects of inheritance, see #5740
  787. __repr_name__ = _repr.Representation.__repr_name__
  788. __repr_str__ = _repr.Representation.__repr_str__
  789. __pretty__ = _repr.Representation.__pretty__
  790. __rich_repr__ = _repr.Representation.__rich_repr__
  791. def __str__(self) -> str:
  792. return self.__repr_str__(' ')
  793. # ##### Deprecated methods from v1 #####
  794. @property
  795. @typing_extensions.deprecated(
  796. 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=PydanticDeprecatedSince20
  797. )
  798. def __fields__(self) -> dict[str, FieldInfo]:
  799. warnings.warn('The `__fields__` attribute is deprecated, use `model_fields` instead.', DeprecationWarning)
  800. return self.model_fields
  801. @property
  802. @typing_extensions.deprecated(
  803. 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
  804. category=PydanticDeprecatedSince20,
  805. )
  806. def __fields_set__(self) -> set[str]:
  807. warnings.warn(
  808. 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', DeprecationWarning
  809. )
  810. return self.__pydantic_fields_set__
  811. @typing_extensions.deprecated(
  812. 'The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20
  813. )
  814. def dict( # noqa: D102
  815. self,
  816. *,
  817. include: IncEx = None,
  818. exclude: IncEx = None,
  819. by_alias: bool = False,
  820. exclude_unset: bool = False,
  821. exclude_defaults: bool = False,
  822. exclude_none: bool = False,
  823. ) -> typing.Dict[str, Any]: # noqa UP006
  824. warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', DeprecationWarning)
  825. return self.model_dump(
  826. include=include,
  827. exclude=exclude,
  828. by_alias=by_alias,
  829. exclude_unset=exclude_unset,
  830. exclude_defaults=exclude_defaults,
  831. exclude_none=exclude_none,
  832. )
  833. @typing_extensions.deprecated(
  834. 'The `json` method is deprecated; use `model_dump_json` instead.', category=PydanticDeprecatedSince20
  835. )
  836. def json( # noqa: D102
  837. self,
  838. *,
  839. include: IncEx = None,
  840. exclude: IncEx = None,
  841. by_alias: bool = False,
  842. exclude_unset: bool = False,
  843. exclude_defaults: bool = False,
  844. exclude_none: bool = False,
  845. encoder: typing.Callable[[Any], Any] | None = PydanticUndefined, # type: ignore[assignment]
  846. models_as_dict: bool = PydanticUndefined, # type: ignore[assignment]
  847. **dumps_kwargs: Any,
  848. ) -> str:
  849. warnings.warn('The `json` method is deprecated; use `model_dump_json` instead.', DeprecationWarning)
  850. if encoder is not PydanticUndefined:
  851. raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.')
  852. if models_as_dict is not PydanticUndefined:
  853. raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.')
  854. if dumps_kwargs:
  855. raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.')
  856. return self.model_dump_json(
  857. include=include,
  858. exclude=exclude,
  859. by_alias=by_alias,
  860. exclude_unset=exclude_unset,
  861. exclude_defaults=exclude_defaults,
  862. exclude_none=exclude_none,
  863. )
  864. @classmethod
  865. @typing_extensions.deprecated(
  866. 'The `parse_obj` method is deprecated; use `model_validate` instead.', category=PydanticDeprecatedSince20
  867. )
  868. def parse_obj(cls: type[Model], obj: Any) -> Model: # noqa: D102
  869. warnings.warn('The `parse_obj` method is deprecated; use `model_validate` instead.', DeprecationWarning)
  870. return cls.model_validate(obj)
  871. @classmethod
  872. @typing_extensions.deprecated(
  873. 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, '
  874. 'otherwise load the data then use `model_validate` instead.',
  875. category=PydanticDeprecatedSince20,
  876. )
  877. def parse_raw( # noqa: D102
  878. cls: type[Model],
  879. b: str | bytes,
  880. *,
  881. content_type: str | None = None,
  882. encoding: str = 'utf8',
  883. proto: DeprecatedParseProtocol | None = None,
  884. allow_pickle: bool = False,
  885. ) -> Model: # pragma: no cover
  886. warnings.warn(
  887. 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, '
  888. 'otherwise load the data then use `model_validate` instead.',
  889. DeprecationWarning,
  890. )
  891. from .deprecated import parse
  892. try:
  893. obj = parse.load_str_bytes(
  894. b,
  895. proto=proto,
  896. content_type=content_type,
  897. encoding=encoding,
  898. allow_pickle=allow_pickle,
  899. )
  900. except (ValueError, TypeError) as exc:
  901. import json
  902. # try to match V1
  903. if isinstance(exc, UnicodeDecodeError):
  904. type_str = 'value_error.unicodedecode'
  905. elif isinstance(exc, json.JSONDecodeError):
  906. type_str = 'value_error.jsondecode'
  907. elif isinstance(exc, ValueError):
  908. type_str = 'value_error'
  909. else:
  910. type_str = 'type_error'
  911. # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same
  912. error: pydantic_core.InitErrorDetails = {
  913. # The type: ignore on the next line is to ignore the requirement of LiteralString
  914. 'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore
  915. 'loc': ('__root__',),
  916. 'input': b,
  917. }
  918. raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error])
  919. return cls.model_validate(obj)
  920. @classmethod
  921. @typing_extensions.deprecated(
  922. 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
  923. 'use `model_validate_json`, otherwise `model_validate` instead.',
  924. category=PydanticDeprecatedSince20,
  925. )
  926. def parse_file( # noqa: D102
  927. cls: type[Model],
  928. path: str | Path,
  929. *,
  930. content_type: str | None = None,
  931. encoding: str = 'utf8',
  932. proto: DeprecatedParseProtocol | None = None,
  933. allow_pickle: bool = False,
  934. ) -> Model:
  935. warnings.warn(
  936. 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
  937. 'use `model_validate_json` otherwise `model_validate` instead.',
  938. DeprecationWarning,
  939. )
  940. from .deprecated import parse
  941. obj = parse.load_file(
  942. path,
  943. proto=proto,
  944. content_type=content_type,
  945. encoding=encoding,
  946. allow_pickle=allow_pickle,
  947. )
  948. return cls.parse_obj(obj)
  949. @classmethod
  950. @typing_extensions.deprecated(
  951. "The `from_orm` method is deprecated; set "
  952. "`model_config['from_attributes']=True` and use `model_validate` instead.",
  953. category=PydanticDeprecatedSince20,
  954. )
  955. def from_orm(cls: type[Model], obj: Any) -> Model: # noqa: D102
  956. warnings.warn(
  957. 'The `from_orm` method is deprecated; set `model_config["from_attributes"]=True` '
  958. 'and use `model_validate` instead.',
  959. DeprecationWarning,
  960. )
  961. if not cls.model_config.get('from_attributes', None):
  962. raise PydanticUserError(
  963. 'You must set the config attribute `from_attributes=True` to use from_orm', code=None
  964. )
  965. return cls.model_validate(obj)
  966. @classmethod
  967. @typing_extensions.deprecated(
  968. 'The `construct` method is deprecated; use `model_construct` instead.', category=PydanticDeprecatedSince20
  969. )
  970. def construct(cls: type[Model], _fields_set: set[str] | None = None, **values: Any) -> Model: # noqa: D102
  971. warnings.warn('The `construct` method is deprecated; use `model_construct` instead.', DeprecationWarning)
  972. return cls.model_construct(_fields_set=_fields_set, **values)
  973. @typing_extensions.deprecated(
  974. 'The copy method is deprecated; use `model_copy` instead.', category=PydanticDeprecatedSince20
  975. )
  976. def copy(
  977. self: Model,
  978. *,
  979. include: AbstractSetIntStr | MappingIntStrAny | None = None,
  980. exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
  981. update: typing.Dict[str, Any] | None = None, # noqa UP006
  982. deep: bool = False,
  983. ) -> Model: # pragma: no cover
  984. """Returns a copy of the model.
  985. !!! warning "Deprecated"
  986. This method is now deprecated; use `model_copy` instead.
  987. If you need `include` or `exclude`, use:
  988. ```py
  989. data = self.model_dump(include=include, exclude=exclude, round_trip=True)
  990. data = {**data, **(update or {})}
  991. copied = self.model_validate(data)
  992. ```
  993. Args:
  994. include: Optional set or mapping
  995. specifying which fields to include in the copied model.
  996. exclude: Optional set or mapping
  997. specifying which fields to exclude in the copied model.
  998. update: Optional dictionary of field-value pairs to override field values
  999. in the copied model.
  1000. deep: If True, the values of fields that are Pydantic models will be deep copied.
  1001. Returns:
  1002. A copy of the model with included, excluded and updated fields as specified.
  1003. """
  1004. warnings.warn(
  1005. 'The `copy` method is deprecated; use `model_copy` instead. '
  1006. 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
  1007. DeprecationWarning,
  1008. )
  1009. from .deprecated import copy_internals
  1010. values = dict(
  1011. copy_internals._iter(
  1012. self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
  1013. ),
  1014. **(update or {}),
  1015. )
  1016. if self.__pydantic_private__ is None:
  1017. private = None
  1018. else:
  1019. private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}
  1020. if self.__pydantic_extra__ is None:
  1021. extra: dict[str, Any] | None = None
  1022. else:
  1023. extra = self.__pydantic_extra__.copy()
  1024. for k in list(self.__pydantic_extra__):
  1025. if k not in values: # k was in the exclude
  1026. extra.pop(k)
  1027. for k in list(values):
  1028. if k in self.__pydantic_extra__: # k must have come from extra
  1029. extra[k] = values.pop(k)
  1030. # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
  1031. if update:
  1032. fields_set = self.__pydantic_fields_set__ | update.keys()
  1033. else:
  1034. fields_set = set(self.__pydantic_fields_set__)
  1035. # removing excluded fields from `__pydantic_fields_set__`
  1036. if exclude:
  1037. fields_set -= set(exclude)
  1038. return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)
  1039. @classmethod
  1040. @typing_extensions.deprecated(
  1041. 'The `schema` method is deprecated; use `model_json_schema` instead.', category=PydanticDeprecatedSince20
  1042. )
  1043. def schema( # noqa: D102
  1044. cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE
  1045. ) -> typing.Dict[str, Any]: # noqa UP006
  1046. warnings.warn('The `schema` method is deprecated; use `model_json_schema` instead.', DeprecationWarning)
  1047. return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template)
  1048. @classmethod
  1049. @typing_extensions.deprecated(
  1050. 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
  1051. category=PydanticDeprecatedSince20,
  1052. )
  1053. def schema_json( # noqa: D102
  1054. cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any
  1055. ) -> str: # pragma: no cover
  1056. import json
  1057. warnings.warn(
  1058. 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
  1059. DeprecationWarning,
  1060. )
  1061. from .deprecated.json import pydantic_encoder
  1062. return json.dumps(
  1063. cls.model_json_schema(by_alias=by_alias, ref_template=ref_template),
  1064. default=pydantic_encoder,
  1065. **dumps_kwargs,
  1066. )
  1067. @classmethod
  1068. @typing_extensions.deprecated(
  1069. 'The `validate` method is deprecated; use `model_validate` instead.', category=PydanticDeprecatedSince20
  1070. )
  1071. def validate(cls: type[Model], value: Any) -> Model: # noqa: D102
  1072. warnings.warn('The `validate` method is deprecated; use `model_validate` instead.', DeprecationWarning)
  1073. return cls.model_validate(value)
  1074. @classmethod
  1075. @typing_extensions.deprecated(
  1076. 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
  1077. category=PydanticDeprecatedSince20,
  1078. )
  1079. def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102
  1080. warnings.warn(
  1081. 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', DeprecationWarning
  1082. )
  1083. if localns: # pragma: no cover
  1084. raise TypeError('`localns` arguments are not longer accepted.')
  1085. cls.model_rebuild(force=True)
  1086. @typing_extensions.deprecated(
  1087. 'The private method `_iter` will be removed and should no longer be used.', category=PydanticDeprecatedSince20
  1088. )
  1089. def _iter(self, *args: Any, **kwargs: Any) -> Any:
  1090. warnings.warn('The private method `_iter` will be removed and should no longer be used.', DeprecationWarning)
  1091. from .deprecated import copy_internals
  1092. return copy_internals._iter(self, *args, **kwargs)
  1093. @typing_extensions.deprecated(
  1094. 'The private method `_copy_and_set_values` will be removed and should no longer be used.',
  1095. category=PydanticDeprecatedSince20,
  1096. )
  1097. def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any:
  1098. warnings.warn(
  1099. 'The private method `_copy_and_set_values` will be removed and should no longer be used.',
  1100. DeprecationWarning,
  1101. )
  1102. from .deprecated import copy_internals
  1103. return copy_internals._copy_and_set_values(self, *args, **kwargs)
  1104. @classmethod
  1105. @typing_extensions.deprecated(
  1106. 'The private method `_get_value` will be removed and should no longer be used.',
  1107. category=PydanticDeprecatedSince20,
  1108. )
  1109. def _get_value(cls, *args: Any, **kwargs: Any) -> Any:
  1110. warnings.warn(
  1111. 'The private method `_get_value` will be removed and should no longer be used.', DeprecationWarning
  1112. )
  1113. from .deprecated import copy_internals
  1114. return copy_internals._get_value(cls, *args, **kwargs)
  1115. @typing_extensions.deprecated(
  1116. 'The private method `_calculate_keys` will be removed and should no longer be used.',
  1117. category=PydanticDeprecatedSince20,
  1118. )
  1119. def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any:
  1120. warnings.warn(
  1121. 'The private method `_calculate_keys` will be removed and should no longer be used.', DeprecationWarning
  1122. )
  1123. from .deprecated import copy_internals
  1124. return copy_internals._calculate_keys(self, *args, **kwargs)
  1125. @typing.overload
  1126. def create_model(
  1127. __model_name: str,
  1128. *,
  1129. __config__: ConfigDict | None = None,
  1130. __base__: None = None,
  1131. __module__: str = __name__,
  1132. __validators__: dict[str, AnyClassMethod] | None = None,
  1133. __cls_kwargs__: dict[str, Any] | None = None,
  1134. **field_definitions: Any,
  1135. ) -> type[BaseModel]:
  1136. ...
  1137. @typing.overload
  1138. def create_model(
  1139. __model_name: str,
  1140. *,
  1141. __config__: ConfigDict | None = None,
  1142. __base__: type[Model] | tuple[type[Model], ...],
  1143. __module__: str = __name__,
  1144. __validators__: dict[str, AnyClassMethod] | None = None,
  1145. __cls_kwargs__: dict[str, Any] | None = None,
  1146. **field_definitions: Any,
  1147. ) -> type[Model]:
  1148. ...
  1149. def create_model(
  1150. __model_name: str,
  1151. *,
  1152. __config__: ConfigDict | None = None,
  1153. __base__: type[Model] | tuple[type[Model], ...] | None = None,
  1154. __module__: str = __name__,
  1155. __validators__: dict[str, AnyClassMethod] | None = None,
  1156. __cls_kwargs__: dict[str, Any] | None = None,
  1157. __slots__: tuple[str, ...] | None = None,
  1158. **field_definitions: Any,
  1159. ) -> type[Model]:
  1160. """Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a
  1161. subclass of [`BaseModel`][pydantic.BaseModel].
  1162. Args:
  1163. __model_name: The name of the newly created model.
  1164. __config__: The configuration of the new model.
  1165. __base__: The base class for the new model.
  1166. __module__: The name of the module that the model belongs to.
  1167. __validators__: A dictionary of methods that validate
  1168. fields.
  1169. __cls_kwargs__: A dictionary of keyword arguments for class creation.
  1170. __slots__: Deprecated. Should not be passed to `create_model`.
  1171. **field_definitions: Attributes of the new model. They should be passed in the format:
  1172. `<name>=(<type>, <default value>)` or `<name>=(<type>, <FieldInfo>)`.
  1173. Returns:
  1174. The new [model][pydantic.BaseModel].
  1175. Raises:
  1176. PydanticUserError: If `__base__` and `__config__` are both passed.
  1177. """
  1178. if __slots__ is not None:
  1179. # __slots__ will be ignored from here on
  1180. warnings.warn('__slots__ should not be passed to create_model', RuntimeWarning)
  1181. if __base__ is not None:
  1182. if __config__ is not None:
  1183. raise PydanticUserError(
  1184. 'to avoid confusion `__config__` and `__base__` cannot be used together',
  1185. code='create-model-config-base',
  1186. )
  1187. if not isinstance(__base__, tuple):
  1188. __base__ = (__base__,)
  1189. else:
  1190. __base__ = (typing.cast(typing.Type['Model'], BaseModel),)
  1191. __cls_kwargs__ = __cls_kwargs__ or {}
  1192. fields = {}
  1193. annotations = {}
  1194. for f_name, f_def in field_definitions.items():
  1195. if not _fields.is_valid_field_name(f_name):
  1196. warnings.warn(f'fields may not start with an underscore, ignoring "{f_name}"', RuntimeWarning)
  1197. if isinstance(f_def, tuple):
  1198. f_def = typing.cast('tuple[str, Any]', f_def)
  1199. try:
  1200. f_annotation, f_value = f_def
  1201. except ValueError as e:
  1202. raise PydanticUserError(
  1203. 'Field definitions should be a `(<type>, <default>)`.',
  1204. code='create-model-field-definitions',
  1205. ) from e
  1206. else:
  1207. f_annotation, f_value = None, f_def
  1208. if f_annotation:
  1209. annotations[f_name] = f_annotation
  1210. fields[f_name] = f_value
  1211. namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__}
  1212. if __validators__:
  1213. namespace.update(__validators__)
  1214. namespace.update(fields)
  1215. if __config__:
  1216. namespace['model_config'] = _config.ConfigWrapper(__config__).config_dict
  1217. resolved_bases = types.resolve_bases(__base__)
  1218. meta, ns, kwds = types.prepare_class(__model_name, resolved_bases, kwds=__cls_kwargs__)
  1219. if resolved_bases is not __base__:
  1220. ns['__orig_bases__'] = __base__
  1221. namespace.update(ns)
  1222. return meta(__model_name, resolved_bases, namespace, __pydantic_reset_parent_namespace__=False, **kwds)
  1223. __getattr__ = getattr_migration(__name__)