main.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. import sys
  2. import warnings
  3. from abc import ABCMeta
  4. from copy import deepcopy
  5. from enum import Enum
  6. from functools import partial
  7. from pathlib import Path
  8. from types import FunctionType, prepare_class, resolve_bases
  9. from typing import (
  10. TYPE_CHECKING,
  11. AbstractSet,
  12. Any,
  13. Callable,
  14. ClassVar,
  15. Dict,
  16. List,
  17. Mapping,
  18. Optional,
  19. Tuple,
  20. Type,
  21. TypeVar,
  22. Union,
  23. cast,
  24. no_type_check,
  25. overload,
  26. )
  27. from typing_extensions import dataclass_transform
  28. from pydantic.v1.class_validators import ValidatorGroup, extract_root_validators, extract_validators, inherit_validators
  29. from pydantic.v1.config import BaseConfig, Extra, inherit_config, prepare_config
  30. from pydantic.v1.error_wrappers import ErrorWrapper, ValidationError
  31. from pydantic.v1.errors import ConfigError, DictError, ExtraError, MissingError
  32. from pydantic.v1.fields import (
  33. MAPPING_LIKE_SHAPES,
  34. Field,
  35. ModelField,
  36. ModelPrivateAttr,
  37. PrivateAttr,
  38. Undefined,
  39. is_finalvar_with_default_val,
  40. )
  41. from pydantic.v1.json import custom_pydantic_encoder, pydantic_encoder
  42. from pydantic.v1.parse import Protocol, load_file, load_str_bytes
  43. from pydantic.v1.schema import default_ref_template, model_schema
  44. from pydantic.v1.types import PyObject, StrBytes
  45. from pydantic.v1.typing import (
  46. AnyCallable,
  47. get_args,
  48. get_origin,
  49. is_classvar,
  50. is_namedtuple,
  51. is_union,
  52. resolve_annotations,
  53. update_model_forward_refs,
  54. )
  55. from pydantic.v1.utils import (
  56. DUNDER_ATTRIBUTES,
  57. ROOT_KEY,
  58. ClassAttribute,
  59. GetterDict,
  60. Representation,
  61. ValueItems,
  62. generate_model_signature,
  63. is_valid_field,
  64. is_valid_private_name,
  65. lenient_issubclass,
  66. sequence_like,
  67. smart_deepcopy,
  68. unique_list,
  69. validate_field_name,
  70. )
  71. if TYPE_CHECKING:
  72. from inspect import Signature
  73. from pydantic.v1.class_validators import ValidatorListDict
  74. from pydantic.v1.types import ModelOrDc
  75. from pydantic.v1.typing import (
  76. AbstractSetIntStr,
  77. AnyClassMethod,
  78. CallableGenerator,
  79. DictAny,
  80. DictStrAny,
  81. MappingIntStrAny,
  82. ReprArgs,
  83. SetStr,
  84. TupleGenerator,
  85. )
  86. Model = TypeVar('Model', bound='BaseModel')
  87. __all__ = 'BaseModel', 'create_model', 'validate_model'
  88. _T = TypeVar('_T')
  89. def validate_custom_root_type(fields: Dict[str, ModelField]) -> None:
  90. if len(fields) > 1:
  91. raise ValueError(f'{ROOT_KEY} cannot be mixed with other fields')
  92. def generate_hash_function(frozen: bool) -> Optional[Callable[[Any], int]]:
  93. def hash_function(self_: Any) -> int:
  94. return hash(self_.__class__) + hash(tuple(self_.__dict__.values()))
  95. return hash_function if frozen else None
  96. # If a field is of type `Callable`, its default value should be a function and cannot to ignored.
  97. ANNOTATED_FIELD_UNTOUCHED_TYPES: Tuple[Any, ...] = (property, type, classmethod, staticmethod)
  98. # When creating a `BaseModel` instance, we bypass all the methods, properties... added to the model
  99. UNTOUCHED_TYPES: Tuple[Any, ...] = (FunctionType,) + ANNOTATED_FIELD_UNTOUCHED_TYPES
  100. # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we need to add this extra
  101. # (somewhat hacky) boolean to keep track of whether we've created the `BaseModel` class yet, and therefore whether it's
  102. # safe to refer to it. If it *hasn't* been created, we assume that the `__new__` call we're in the middle of is for
  103. # the `BaseModel` class, since that's defined immediately after the metaclass.
  104. _is_base_model_class_defined = False
  105. @dataclass_transform(kw_only_default=True, field_specifiers=(Field,))
  106. class ModelMetaclass(ABCMeta):
  107. @no_type_check # noqa C901
  108. def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901
  109. fields: Dict[str, ModelField] = {}
  110. config = BaseConfig
  111. validators: 'ValidatorListDict' = {}
  112. pre_root_validators, post_root_validators = [], []
  113. private_attributes: Dict[str, ModelPrivateAttr] = {}
  114. base_private_attributes: Dict[str, ModelPrivateAttr] = {}
  115. slots: SetStr = namespace.get('__slots__', ())
  116. slots = {slots} if isinstance(slots, str) else set(slots)
  117. class_vars: SetStr = set()
  118. hash_func: Optional[Callable[[Any], int]] = None
  119. for base in reversed(bases):
  120. if _is_base_model_class_defined and issubclass(base, BaseModel) and base != BaseModel:
  121. fields.update(smart_deepcopy(base.__fields__))
  122. config = inherit_config(base.__config__, config)
  123. validators = inherit_validators(base.__validators__, validators)
  124. pre_root_validators += base.__pre_root_validators__
  125. post_root_validators += base.__post_root_validators__
  126. base_private_attributes.update(base.__private_attributes__)
  127. class_vars.update(base.__class_vars__)
  128. hash_func = base.__hash__
  129. resolve_forward_refs = kwargs.pop('__resolve_forward_refs__', True)
  130. allowed_config_kwargs: SetStr = {
  131. key
  132. for key in dir(config)
  133. if not (key.startswith('__') and key.endswith('__')) # skip dunder methods and attributes
  134. }
  135. config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & allowed_config_kwargs}
  136. config_from_namespace = namespace.get('Config')
  137. if config_kwargs and config_from_namespace:
  138. raise TypeError('Specifying config in two places is ambiguous, use either Config attribute or class kwargs')
  139. config = inherit_config(config_from_namespace, config, **config_kwargs)
  140. validators = inherit_validators(extract_validators(namespace), validators)
  141. vg = ValidatorGroup(validators)
  142. for f in fields.values():
  143. f.set_config(config)
  144. extra_validators = vg.get_validators(f.name)
  145. if extra_validators:
  146. f.class_validators.update(extra_validators)
  147. # re-run prepare to add extra validators
  148. f.populate_validators()
  149. prepare_config(config, name)
  150. untouched_types = ANNOTATED_FIELD_UNTOUCHED_TYPES
  151. def is_untouched(v: Any) -> bool:
  152. return isinstance(v, untouched_types) or v.__class__.__name__ == 'cython_function_or_method'
  153. if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pydantic.main', 'BaseModel'):
  154. if sys.version_info >= (3, 14):
  155. if '__annotations__' in namespace:
  156. # `from __future__ import annotations` was used in the model's module
  157. raw_annotations = namespace['__annotations__']
  158. else:
  159. # See https://docs.python.org/3/library/annotationlib.html#using-annotations-in-a-metaclass:
  160. from annotationlib import Format, call_annotate_function, get_annotate_from_class_namespace
  161. annotate = get_annotate_from_class_namespace(namespace)
  162. if annotate is not None:
  163. raw_annotations = call_annotate_function(annotate, format=Format.FORWARDREF)
  164. else:
  165. raw_annotations = {}
  166. else:
  167. raw_annotations = namespace.get('__annotations__', {})
  168. annotations = resolve_annotations(raw_annotations, namespace.get('__module__', None))
  169. # annotation only fields need to come first in fields
  170. for ann_name, ann_type in annotations.items():
  171. if is_classvar(ann_type):
  172. class_vars.add(ann_name)
  173. elif is_finalvar_with_default_val(ann_type, namespace.get(ann_name, Undefined)):
  174. class_vars.add(ann_name)
  175. elif is_valid_field(ann_name):
  176. validate_field_name(bases, ann_name)
  177. value = namespace.get(ann_name, Undefined)
  178. allowed_types = get_args(ann_type) if is_union(get_origin(ann_type)) else (ann_type,)
  179. if (
  180. is_untouched(value)
  181. and ann_type != PyObject
  182. and not any(
  183. lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types
  184. )
  185. ):
  186. continue
  187. fields[ann_name] = ModelField.infer(
  188. name=ann_name,
  189. value=value,
  190. annotation=ann_type,
  191. class_validators=vg.get_validators(ann_name),
  192. config=config,
  193. )
  194. elif ann_name not in namespace and config.underscore_attrs_are_private:
  195. private_attributes[ann_name] = PrivateAttr()
  196. untouched_types = UNTOUCHED_TYPES + config.keep_untouched
  197. for var_name, value in namespace.items():
  198. can_be_changed = var_name not in class_vars and not is_untouched(value)
  199. if isinstance(value, ModelPrivateAttr):
  200. if not is_valid_private_name(var_name):
  201. raise NameError(
  202. f'Private attributes "{var_name}" must not be a valid field name; '
  203. f'Use sunder or dunder names, e. g. "_{var_name}" or "__{var_name}__"'
  204. )
  205. private_attributes[var_name] = value
  206. elif config.underscore_attrs_are_private and is_valid_private_name(var_name) and can_be_changed:
  207. private_attributes[var_name] = PrivateAttr(default=value)
  208. elif is_valid_field(var_name) and var_name not in annotations and can_be_changed:
  209. validate_field_name(bases, var_name)
  210. inferred = ModelField.infer(
  211. name=var_name,
  212. value=value,
  213. annotation=annotations.get(var_name, Undefined),
  214. class_validators=vg.get_validators(var_name),
  215. config=config,
  216. )
  217. if var_name in fields:
  218. if lenient_issubclass(inferred.type_, fields[var_name].type_):
  219. inferred.type_ = fields[var_name].type_
  220. else:
  221. raise TypeError(
  222. f'The type of {name}.{var_name} differs from the new default value; '
  223. f'if you wish to change the type of this field, please use a type annotation'
  224. )
  225. fields[var_name] = inferred
  226. _custom_root_type = ROOT_KEY in fields
  227. if _custom_root_type:
  228. validate_custom_root_type(fields)
  229. vg.check_for_unused()
  230. if config.json_encoders:
  231. json_encoder = partial(custom_pydantic_encoder, config.json_encoders)
  232. else:
  233. json_encoder = pydantic_encoder
  234. pre_rv_new, post_rv_new = extract_root_validators(namespace)
  235. if hash_func is None:
  236. hash_func = generate_hash_function(config.frozen)
  237. exclude_from_namespace = fields | private_attributes.keys() | {'__slots__'}
  238. new_namespace = {
  239. '__config__': config,
  240. '__fields__': fields,
  241. '__exclude_fields__': {
  242. name: field.field_info.exclude for name, field in fields.items() if field.field_info.exclude is not None
  243. }
  244. or None,
  245. '__include_fields__': {
  246. name: field.field_info.include for name, field in fields.items() if field.field_info.include is not None
  247. }
  248. or None,
  249. '__validators__': vg.validators,
  250. '__pre_root_validators__': unique_list(
  251. pre_root_validators + pre_rv_new,
  252. name_factory=lambda v: v.__name__,
  253. ),
  254. '__post_root_validators__': unique_list(
  255. post_root_validators + post_rv_new,
  256. name_factory=lambda skip_on_failure_and_v: skip_on_failure_and_v[1].__name__,
  257. ),
  258. '__schema_cache__': {},
  259. '__json_encoder__': staticmethod(json_encoder),
  260. '__custom_root_type__': _custom_root_type,
  261. '__private_attributes__': {**base_private_attributes, **private_attributes},
  262. '__slots__': slots | private_attributes.keys(),
  263. '__hash__': hash_func,
  264. '__class_vars__': class_vars,
  265. **{n: v for n, v in namespace.items() if n not in exclude_from_namespace},
  266. }
  267. cls = super().__new__(mcs, name, bases, new_namespace, **kwargs)
  268. # set __signature__ attr only for model class, but not for its instances
  269. cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config))
  270. if not _is_base_model_class_defined:
  271. # Cython does not understand the `if TYPE_CHECKING:` condition in the
  272. # BaseModel's body (where annotations are set), so clear them manually:
  273. getattr(cls, '__annotations__', {}).clear()
  274. if resolve_forward_refs:
  275. cls.__try_update_forward_refs__()
  276. # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487
  277. # for attributes not in `new_namespace` (e.g. private attributes)
  278. for name, obj in namespace.items():
  279. if name not in new_namespace:
  280. set_name = getattr(obj, '__set_name__', None)
  281. if callable(set_name):
  282. set_name(cls, name)
  283. return cls
  284. def __instancecheck__(self, instance: Any) -> bool:
  285. """
  286. Avoid calling ABC _abc_subclasscheck unless we're pretty sure.
  287. See #3829 and python/cpython#92810
  288. """
  289. return hasattr(instance, '__post_root_validators__') and super().__instancecheck__(instance)
  290. object_setattr = object.__setattr__
  291. class BaseModel(Representation, metaclass=ModelMetaclass):
  292. if TYPE_CHECKING:
  293. # populated by the metaclass, defined here to help IDEs only
  294. __fields__: ClassVar[Dict[str, ModelField]] = {}
  295. __include_fields__: ClassVar[Optional[Mapping[str, Any]]] = None
  296. __exclude_fields__: ClassVar[Optional[Mapping[str, Any]]] = None
  297. __validators__: ClassVar[Dict[str, AnyCallable]] = {}
  298. __pre_root_validators__: ClassVar[List[AnyCallable]]
  299. __post_root_validators__: ClassVar[List[Tuple[bool, AnyCallable]]]
  300. __config__: ClassVar[Type[BaseConfig]] = BaseConfig
  301. __json_encoder__: ClassVar[Callable[[Any], Any]] = lambda x: x
  302. __schema_cache__: ClassVar['DictAny'] = {}
  303. __custom_root_type__: ClassVar[bool] = False
  304. __signature__: ClassVar['Signature']
  305. __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]]
  306. __class_vars__: ClassVar[SetStr]
  307. __fields_set__: ClassVar[SetStr] = set()
  308. Config = BaseConfig
  309. __slots__ = ('__dict__', '__fields_set__')
  310. __doc__ = '' # Null out the Representation docstring
  311. def __init__(__pydantic_self__, **data: Any) -> None:
  312. """
  313. Create a new model by parsing and validating input data from keyword arguments.
  314. Raises ValidationError if the input data cannot be parsed to form a valid model.
  315. """
  316. # Uses something other than `self` the first arg to allow "self" as a settable attribute
  317. values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data)
  318. if validation_error:
  319. raise validation_error
  320. try:
  321. object_setattr(__pydantic_self__, '__dict__', values)
  322. except TypeError as e:
  323. raise TypeError(
  324. 'Model values must be a dict; you may not have returned a dictionary from a root validator'
  325. ) from e
  326. object_setattr(__pydantic_self__, '__fields_set__', fields_set)
  327. __pydantic_self__._init_private_attributes()
  328. @no_type_check
  329. def __setattr__(self, name, value): # noqa: C901 (ignore complexity)
  330. if name in self.__private_attributes__ or name in DUNDER_ATTRIBUTES:
  331. return object_setattr(self, name, value)
  332. if self.__config__.extra is not Extra.allow and name not in self.__fields__:
  333. raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
  334. elif not self.__config__.allow_mutation or self.__config__.frozen:
  335. raise TypeError(f'"{self.__class__.__name__}" is immutable and does not support item assignment')
  336. elif name in self.__fields__ and self.__fields__[name].final:
  337. raise TypeError(
  338. f'"{self.__class__.__name__}" object "{name}" field is final and does not support reassignment'
  339. )
  340. elif self.__config__.validate_assignment:
  341. new_values = {**self.__dict__, name: value}
  342. for validator in self.__pre_root_validators__:
  343. try:
  344. new_values = validator(self.__class__, new_values)
  345. except (ValueError, TypeError, AssertionError) as exc:
  346. raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], self.__class__)
  347. known_field = self.__fields__.get(name, None)
  348. if known_field:
  349. # We want to
  350. # - make sure validators are called without the current value for this field inside `values`
  351. # - keep other values (e.g. submodels) untouched (using `BaseModel.dict()` will change them into dicts)
  352. # - keep the order of the fields
  353. if not known_field.field_info.allow_mutation:
  354. raise TypeError(f'"{known_field.name}" has allow_mutation set to False and cannot be assigned')
  355. dict_without_original_value = {k: v for k, v in self.__dict__.items() if k != name}
  356. value, error_ = known_field.validate(value, dict_without_original_value, loc=name, cls=self.__class__)
  357. if error_:
  358. raise ValidationError([error_], self.__class__)
  359. else:
  360. new_values[name] = value
  361. errors = []
  362. for skip_on_failure, validator in self.__post_root_validators__:
  363. if skip_on_failure and errors:
  364. continue
  365. try:
  366. new_values = validator(self.__class__, new_values)
  367. except (ValueError, TypeError, AssertionError) as exc:
  368. errors.append(ErrorWrapper(exc, loc=ROOT_KEY))
  369. if errors:
  370. raise ValidationError(errors, self.__class__)
  371. # update the whole __dict__ as other values than just `value`
  372. # may be changed (e.g. with `root_validator`)
  373. object_setattr(self, '__dict__', new_values)
  374. else:
  375. self.__dict__[name] = value
  376. self.__fields_set__.add(name)
  377. def __getstate__(self) -> 'DictAny':
  378. private_attrs = ((k, getattr(self, k, Undefined)) for k in self.__private_attributes__)
  379. return {
  380. '__dict__': self.__dict__,
  381. '__fields_set__': self.__fields_set__,
  382. '__private_attribute_values__': {k: v for k, v in private_attrs if v is not Undefined},
  383. }
  384. def __setstate__(self, state: 'DictAny') -> None:
  385. object_setattr(self, '__dict__', state['__dict__'])
  386. object_setattr(self, '__fields_set__', state['__fields_set__'])
  387. for name, value in state.get('__private_attribute_values__', {}).items():
  388. object_setattr(self, name, value)
  389. def _init_private_attributes(self) -> None:
  390. for name, private_attr in self.__private_attributes__.items():
  391. default = private_attr.get_default()
  392. if default is not Undefined:
  393. object_setattr(self, name, default)
  394. def dict(
  395. self,
  396. *,
  397. include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  398. exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  399. by_alias: bool = False,
  400. skip_defaults: Optional[bool] = None,
  401. exclude_unset: bool = False,
  402. exclude_defaults: bool = False,
  403. exclude_none: bool = False,
  404. ) -> 'DictStrAny':
  405. """
  406. Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
  407. """
  408. if skip_defaults is not None:
  409. warnings.warn(
  410. f'{self.__class__.__name__}.dict(): "skip_defaults" is deprecated and replaced by "exclude_unset"',
  411. DeprecationWarning,
  412. )
  413. exclude_unset = skip_defaults
  414. return dict(
  415. self._iter(
  416. to_dict=True,
  417. by_alias=by_alias,
  418. include=include,
  419. exclude=exclude,
  420. exclude_unset=exclude_unset,
  421. exclude_defaults=exclude_defaults,
  422. exclude_none=exclude_none,
  423. )
  424. )
  425. def json(
  426. self,
  427. *,
  428. include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  429. exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  430. by_alias: bool = False,
  431. skip_defaults: Optional[bool] = None,
  432. exclude_unset: bool = False,
  433. exclude_defaults: bool = False,
  434. exclude_none: bool = False,
  435. encoder: Optional[Callable[[Any], Any]] = None,
  436. models_as_dict: bool = True,
  437. **dumps_kwargs: Any,
  438. ) -> str:
  439. """
  440. Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`.
  441. `encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`.
  442. """
  443. if skip_defaults is not None:
  444. warnings.warn(
  445. f'{self.__class__.__name__}.json(): "skip_defaults" is deprecated and replaced by "exclude_unset"',
  446. DeprecationWarning,
  447. )
  448. exclude_unset = skip_defaults
  449. encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__)
  450. # We don't directly call `self.dict()`, which does exactly this with `to_dict=True`
  451. # because we want to be able to keep raw `BaseModel` instances and not as `dict`.
  452. # This allows users to write custom JSON encoders for given `BaseModel` classes.
  453. data = dict(
  454. self._iter(
  455. to_dict=models_as_dict,
  456. by_alias=by_alias,
  457. include=include,
  458. exclude=exclude,
  459. exclude_unset=exclude_unset,
  460. exclude_defaults=exclude_defaults,
  461. exclude_none=exclude_none,
  462. )
  463. )
  464. if self.__custom_root_type__:
  465. data = data[ROOT_KEY]
  466. return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs)
  467. @classmethod
  468. def _enforce_dict_if_root(cls, obj: Any) -> Any:
  469. if cls.__custom_root_type__ and (
  470. not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY})
  471. and not (isinstance(obj, BaseModel) and obj.__fields__.keys() == {ROOT_KEY})
  472. or cls.__fields__[ROOT_KEY].shape in MAPPING_LIKE_SHAPES
  473. ):
  474. return {ROOT_KEY: obj}
  475. else:
  476. return obj
  477. @classmethod
  478. def parse_obj(cls: Type['Model'], obj: Any) -> 'Model':
  479. obj = cls._enforce_dict_if_root(obj)
  480. if not isinstance(obj, dict):
  481. try:
  482. obj = dict(obj)
  483. except (TypeError, ValueError) as e:
  484. exc = TypeError(f'{cls.__name__} expected dict not {obj.__class__.__name__}')
  485. raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e
  486. return cls(**obj)
  487. @classmethod
  488. def parse_raw(
  489. cls: Type['Model'],
  490. b: StrBytes,
  491. *,
  492. content_type: str = None,
  493. encoding: str = 'utf8',
  494. proto: Protocol = None,
  495. allow_pickle: bool = False,
  496. ) -> 'Model':
  497. try:
  498. obj = load_str_bytes(
  499. b,
  500. proto=proto,
  501. content_type=content_type,
  502. encoding=encoding,
  503. allow_pickle=allow_pickle,
  504. json_loads=cls.__config__.json_loads,
  505. )
  506. except (ValueError, TypeError, UnicodeDecodeError) as e:
  507. raise ValidationError([ErrorWrapper(e, loc=ROOT_KEY)], cls)
  508. return cls.parse_obj(obj)
  509. @classmethod
  510. def parse_file(
  511. cls: Type['Model'],
  512. path: Union[str, Path],
  513. *,
  514. content_type: str = None,
  515. encoding: str = 'utf8',
  516. proto: Protocol = None,
  517. allow_pickle: bool = False,
  518. ) -> 'Model':
  519. obj = load_file(
  520. path,
  521. proto=proto,
  522. content_type=content_type,
  523. encoding=encoding,
  524. allow_pickle=allow_pickle,
  525. json_loads=cls.__config__.json_loads,
  526. )
  527. return cls.parse_obj(obj)
  528. @classmethod
  529. def from_orm(cls: Type['Model'], obj: Any) -> 'Model':
  530. if not cls.__config__.orm_mode:
  531. raise ConfigError('You must have the config attribute orm_mode=True to use from_orm')
  532. obj = {ROOT_KEY: obj} if cls.__custom_root_type__ else cls._decompose_class(obj)
  533. m = cls.__new__(cls)
  534. values, fields_set, validation_error = validate_model(cls, obj)
  535. if validation_error:
  536. raise validation_error
  537. object_setattr(m, '__dict__', values)
  538. object_setattr(m, '__fields_set__', fields_set)
  539. m._init_private_attributes()
  540. return m
  541. @classmethod
  542. def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **values: Any) -> 'Model':
  543. """
  544. Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
  545. Default values are respected, but no other validation is performed.
  546. Behaves as if `Config.extra = 'allow'` was set since it adds all passed values
  547. """
  548. m = cls.__new__(cls)
  549. fields_values: Dict[str, Any] = {}
  550. for name, field in cls.__fields__.items():
  551. if field.alt_alias and field.alias in values:
  552. fields_values[name] = values[field.alias]
  553. elif name in values:
  554. fields_values[name] = values[name]
  555. elif not field.required:
  556. fields_values[name] = field.get_default()
  557. fields_values.update(values)
  558. object_setattr(m, '__dict__', fields_values)
  559. if _fields_set is None:
  560. _fields_set = set(values.keys())
  561. object_setattr(m, '__fields_set__', _fields_set)
  562. m._init_private_attributes()
  563. return m
  564. def _copy_and_set_values(self: 'Model', values: 'DictStrAny', fields_set: 'SetStr', *, deep: bool) -> 'Model':
  565. if deep:
  566. # chances of having empty dict here are quite low for using smart_deepcopy
  567. values = deepcopy(values)
  568. cls = self.__class__
  569. m = cls.__new__(cls)
  570. object_setattr(m, '__dict__', values)
  571. object_setattr(m, '__fields_set__', fields_set)
  572. for name in self.__private_attributes__:
  573. value = getattr(self, name, Undefined)
  574. if value is not Undefined:
  575. if deep:
  576. value = deepcopy(value)
  577. object_setattr(m, name, value)
  578. return m
  579. def copy(
  580. self: 'Model',
  581. *,
  582. include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  583. exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  584. update: Optional['DictStrAny'] = None,
  585. deep: bool = False,
  586. ) -> 'Model':
  587. """
  588. Duplicate a model, optionally choose which fields to include, exclude and change.
  589. :param include: fields to include in new model
  590. :param exclude: fields to exclude from new model, as with values this takes precedence over include
  591. :param update: values to change/add in the new model. Note: the data is not validated before creating
  592. the new model: you should trust this data
  593. :param deep: set to `True` to make a deep copy of the model
  594. :return: new model instance
  595. """
  596. values = dict(
  597. self._iter(to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False),
  598. **(update or {}),
  599. )
  600. # new `__fields_set__` can have unset optional fields with a set value in `update` kwarg
  601. if update:
  602. fields_set = self.__fields_set__ | update.keys()
  603. else:
  604. fields_set = set(self.__fields_set__)
  605. return self._copy_and_set_values(values, fields_set, deep=deep)
  606. @classmethod
  607. def schema(cls, by_alias: bool = True, ref_template: str = default_ref_template) -> 'DictStrAny':
  608. cached = cls.__schema_cache__.get((by_alias, ref_template))
  609. if cached is not None:
  610. return cached
  611. s = model_schema(cls, by_alias=by_alias, ref_template=ref_template)
  612. cls.__schema_cache__[(by_alias, ref_template)] = s
  613. return s
  614. @classmethod
  615. def schema_json(
  616. cls, *, by_alias: bool = True, ref_template: str = default_ref_template, **dumps_kwargs: Any
  617. ) -> str:
  618. from pydantic.v1.json import pydantic_encoder
  619. return cls.__config__.json_dumps(
  620. cls.schema(by_alias=by_alias, ref_template=ref_template), default=pydantic_encoder, **dumps_kwargs
  621. )
  622. @classmethod
  623. def __get_validators__(cls) -> 'CallableGenerator':
  624. yield cls.validate
  625. @classmethod
  626. def validate(cls: Type['Model'], value: Any) -> 'Model':
  627. if isinstance(value, cls):
  628. copy_on_model_validation = cls.__config__.copy_on_model_validation
  629. # whether to deep or shallow copy the model on validation, None means do not copy
  630. deep_copy: Optional[bool] = None
  631. if copy_on_model_validation not in {'deep', 'shallow', 'none'}:
  632. # Warn about deprecated behavior
  633. warnings.warn(
  634. "`copy_on_model_validation` should be a string: 'deep', 'shallow' or 'none'", DeprecationWarning
  635. )
  636. if copy_on_model_validation:
  637. deep_copy = False
  638. if copy_on_model_validation == 'shallow':
  639. # shallow copy
  640. deep_copy = False
  641. elif copy_on_model_validation == 'deep':
  642. # deep copy
  643. deep_copy = True
  644. if deep_copy is None:
  645. return value
  646. else:
  647. return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=deep_copy)
  648. value = cls._enforce_dict_if_root(value)
  649. if isinstance(value, dict):
  650. return cls(**value)
  651. elif cls.__config__.orm_mode:
  652. return cls.from_orm(value)
  653. else:
  654. try:
  655. value_as_dict = dict(value)
  656. except (TypeError, ValueError) as e:
  657. raise DictError() from e
  658. return cls(**value_as_dict)
  659. @classmethod
  660. def _decompose_class(cls: Type['Model'], obj: Any) -> GetterDict:
  661. if isinstance(obj, GetterDict):
  662. return obj
  663. return cls.__config__.getter_dict(obj)
  664. @classmethod
  665. @no_type_check
  666. def _get_value(
  667. cls,
  668. v: Any,
  669. to_dict: bool,
  670. by_alias: bool,
  671. include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
  672. exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
  673. exclude_unset: bool,
  674. exclude_defaults: bool,
  675. exclude_none: bool,
  676. ) -> Any:
  677. if isinstance(v, BaseModel):
  678. if to_dict:
  679. v_dict = v.dict(
  680. by_alias=by_alias,
  681. exclude_unset=exclude_unset,
  682. exclude_defaults=exclude_defaults,
  683. include=include,
  684. exclude=exclude,
  685. exclude_none=exclude_none,
  686. )
  687. if ROOT_KEY in v_dict:
  688. return v_dict[ROOT_KEY]
  689. return v_dict
  690. else:
  691. return v.copy(include=include, exclude=exclude)
  692. value_exclude = ValueItems(v, exclude) if exclude else None
  693. value_include = ValueItems(v, include) if include else None
  694. if isinstance(v, dict):
  695. return {
  696. k_: cls._get_value(
  697. v_,
  698. to_dict=to_dict,
  699. by_alias=by_alias,
  700. exclude_unset=exclude_unset,
  701. exclude_defaults=exclude_defaults,
  702. include=value_include and value_include.for_element(k_),
  703. exclude=value_exclude and value_exclude.for_element(k_),
  704. exclude_none=exclude_none,
  705. )
  706. for k_, v_ in v.items()
  707. if (not value_exclude or not value_exclude.is_excluded(k_))
  708. and (not value_include or value_include.is_included(k_))
  709. }
  710. elif sequence_like(v):
  711. seq_args = (
  712. cls._get_value(
  713. v_,
  714. to_dict=to_dict,
  715. by_alias=by_alias,
  716. exclude_unset=exclude_unset,
  717. exclude_defaults=exclude_defaults,
  718. include=value_include and value_include.for_element(i),
  719. exclude=value_exclude and value_exclude.for_element(i),
  720. exclude_none=exclude_none,
  721. )
  722. for i, v_ in enumerate(v)
  723. if (not value_exclude or not value_exclude.is_excluded(i))
  724. and (not value_include or value_include.is_included(i))
  725. )
  726. return v.__class__(*seq_args) if is_namedtuple(v.__class__) else v.__class__(seq_args)
  727. elif isinstance(v, Enum) and getattr(cls.Config, 'use_enum_values', False):
  728. return v.value
  729. else:
  730. return v
  731. @classmethod
  732. def __try_update_forward_refs__(cls, **localns: Any) -> None:
  733. """
  734. Same as update_forward_refs but will not raise exception
  735. when forward references are not defined.
  736. """
  737. update_model_forward_refs(cls, cls.__fields__.values(), cls.__config__.json_encoders, localns, (NameError,))
  738. @classmethod
  739. def update_forward_refs(cls, **localns: Any) -> None:
  740. """
  741. Try to update ForwardRefs on fields based on this Model, globalns and localns.
  742. """
  743. update_model_forward_refs(cls, cls.__fields__.values(), cls.__config__.json_encoders, localns)
  744. def __iter__(self) -> 'TupleGenerator':
  745. """
  746. so `dict(model)` works
  747. """
  748. yield from self.__dict__.items()
  749. def _iter(
  750. self,
  751. to_dict: bool = False,
  752. by_alias: bool = False,
  753. include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  754. exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None,
  755. exclude_unset: bool = False,
  756. exclude_defaults: bool = False,
  757. exclude_none: bool = False,
  758. ) -> 'TupleGenerator':
  759. # Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
  760. # The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
  761. if exclude is not None or self.__exclude_fields__ is not None:
  762. exclude = ValueItems.merge(self.__exclude_fields__, exclude)
  763. if include is not None or self.__include_fields__ is not None:
  764. include = ValueItems.merge(self.__include_fields__, include, intersect=True)
  765. allowed_keys = self._calculate_keys(
  766. include=include, exclude=exclude, exclude_unset=exclude_unset # type: ignore
  767. )
  768. if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none):
  769. # huge boost for plain _iter()
  770. yield from self.__dict__.items()
  771. return
  772. value_exclude = ValueItems(self, exclude) if exclude is not None else None
  773. value_include = ValueItems(self, include) if include is not None else None
  774. for field_key, v in self.__dict__.items():
  775. if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None):
  776. continue
  777. if exclude_defaults:
  778. model_field = self.__fields__.get(field_key)
  779. if not getattr(model_field, 'required', True) and getattr(model_field, 'default', _missing) == v:
  780. continue
  781. if by_alias and field_key in self.__fields__:
  782. dict_key = self.__fields__[field_key].alias
  783. else:
  784. dict_key = field_key
  785. if to_dict or value_include or value_exclude:
  786. v = self._get_value(
  787. v,
  788. to_dict=to_dict,
  789. by_alias=by_alias,
  790. include=value_include and value_include.for_element(field_key),
  791. exclude=value_exclude and value_exclude.for_element(field_key),
  792. exclude_unset=exclude_unset,
  793. exclude_defaults=exclude_defaults,
  794. exclude_none=exclude_none,
  795. )
  796. yield dict_key, v
  797. def _calculate_keys(
  798. self,
  799. include: Optional['MappingIntStrAny'],
  800. exclude: Optional['MappingIntStrAny'],
  801. exclude_unset: bool,
  802. update: Optional['DictStrAny'] = None,
  803. ) -> Optional[AbstractSet[str]]:
  804. if include is None and exclude is None and exclude_unset is False:
  805. return None
  806. keys: AbstractSet[str]
  807. if exclude_unset:
  808. keys = self.__fields_set__.copy()
  809. else:
  810. keys = self.__dict__.keys()
  811. if include is not None:
  812. keys &= include.keys()
  813. if update:
  814. keys -= update.keys()
  815. if exclude:
  816. keys -= {k for k, v in exclude.items() if ValueItems.is_true(v)}
  817. return keys
  818. def __eq__(self, other: Any) -> bool:
  819. if isinstance(other, BaseModel):
  820. return self.dict() == other.dict()
  821. else:
  822. return self.dict() == other
  823. def __repr_args__(self) -> 'ReprArgs':
  824. return [
  825. (k, v)
  826. for k, v in self.__dict__.items()
  827. if k not in DUNDER_ATTRIBUTES and (k not in self.__fields__ or self.__fields__[k].field_info.repr)
  828. ]
  829. _is_base_model_class_defined = True
  830. @overload
  831. def create_model(
  832. __model_name: str,
  833. *,
  834. __config__: Optional[Type[BaseConfig]] = None,
  835. __base__: None = None,
  836. __module__: str = __name__,
  837. __validators__: Dict[str, 'AnyClassMethod'] = None,
  838. __cls_kwargs__: Dict[str, Any] = None,
  839. **field_definitions: Any,
  840. ) -> Type['BaseModel']:
  841. ...
  842. @overload
  843. def create_model(
  844. __model_name: str,
  845. *,
  846. __config__: Optional[Type[BaseConfig]] = None,
  847. __base__: Union[Type['Model'], Tuple[Type['Model'], ...]],
  848. __module__: str = __name__,
  849. __validators__: Dict[str, 'AnyClassMethod'] = None,
  850. __cls_kwargs__: Dict[str, Any] = None,
  851. **field_definitions: Any,
  852. ) -> Type['Model']:
  853. ...
  854. def create_model(
  855. __model_name: str,
  856. *,
  857. __config__: Optional[Type[BaseConfig]] = None,
  858. __base__: Union[None, Type['Model'], Tuple[Type['Model'], ...]] = None,
  859. __module__: str = __name__,
  860. __validators__: Dict[str, 'AnyClassMethod'] = None,
  861. __cls_kwargs__: Dict[str, Any] = None,
  862. __slots__: Optional[Tuple[str, ...]] = None,
  863. **field_definitions: Any,
  864. ) -> Type['Model']:
  865. """
  866. Dynamically create a model.
  867. :param __model_name: name of the created model
  868. :param __config__: config class to use for the new model
  869. :param __base__: base class for the new model to inherit from
  870. :param __module__: module of the created model
  871. :param __validators__: a dict of method names and @validator class methods
  872. :param __cls_kwargs__: a dict for class creation
  873. :param __slots__: Deprecated, `__slots__` should not be passed to `create_model`
  874. :param field_definitions: fields of the model (or extra fields if a base is supplied)
  875. in the format `<name>=(<type>, <default default>)` or `<name>=<default value>, e.g.
  876. `foobar=(str, ...)` or `foobar=123`, or, for complex use-cases, in the format
  877. `<name>=<Field>` or `<name>=(<type>, <FieldInfo>)`, e.g.
  878. `foo=Field(datetime, default_factory=datetime.utcnow, alias='bar')` or
  879. `foo=(str, FieldInfo(title='Foo'))`
  880. """
  881. if __slots__ is not None:
  882. # __slots__ will be ignored from here on
  883. warnings.warn('__slots__ should not be passed to create_model', RuntimeWarning)
  884. if __base__ is not None:
  885. if __config__ is not None:
  886. raise ConfigError('to avoid confusion __config__ and __base__ cannot be used together')
  887. if not isinstance(__base__, tuple):
  888. __base__ = (__base__,)
  889. else:
  890. __base__ = (cast(Type['Model'], BaseModel),)
  891. __cls_kwargs__ = __cls_kwargs__ or {}
  892. fields = {}
  893. annotations = {}
  894. for f_name, f_def in field_definitions.items():
  895. if not is_valid_field(f_name):
  896. warnings.warn(f'fields may not start with an underscore, ignoring "{f_name}"', RuntimeWarning)
  897. if isinstance(f_def, tuple):
  898. try:
  899. f_annotation, f_value = f_def
  900. except ValueError as e:
  901. raise ConfigError(
  902. 'field definitions should either be a tuple of (<type>, <default>) or just a '
  903. 'default value, unfortunately this means tuples as '
  904. 'default values are not allowed'
  905. ) from e
  906. else:
  907. f_annotation, f_value = None, f_def
  908. if f_annotation:
  909. annotations[f_name] = f_annotation
  910. fields[f_name] = f_value
  911. namespace: 'DictStrAny' = {'__annotations__': annotations, '__module__': __module__}
  912. if __validators__:
  913. namespace.update(__validators__)
  914. namespace.update(fields)
  915. if __config__:
  916. namespace['Config'] = inherit_config(__config__, BaseConfig)
  917. resolved_bases = resolve_bases(__base__)
  918. meta, ns, kwds = prepare_class(__model_name, resolved_bases, kwds=__cls_kwargs__)
  919. if resolved_bases is not __base__:
  920. ns['__orig_bases__'] = __base__
  921. namespace.update(ns)
  922. return meta(__model_name, resolved_bases, namespace, **kwds)
  923. _missing = object()
  924. def validate_model( # noqa: C901 (ignore complexity)
  925. model: Type[BaseModel], input_data: 'DictStrAny', cls: 'ModelOrDc' = None
  926. ) -> Tuple['DictStrAny', 'SetStr', Optional[ValidationError]]:
  927. """
  928. validate data against a model.
  929. """
  930. values = {}
  931. errors = []
  932. # input_data names, possibly alias
  933. names_used = set()
  934. # field names, never aliases
  935. fields_set = set()
  936. config = model.__config__
  937. check_extra = config.extra is not Extra.ignore
  938. cls_ = cls or model
  939. for validator in model.__pre_root_validators__:
  940. try:
  941. input_data = validator(cls_, input_data)
  942. except (ValueError, TypeError, AssertionError) as exc:
  943. return {}, set(), ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls_)
  944. for name, field in model.__fields__.items():
  945. value = input_data.get(field.alias, _missing)
  946. using_name = False
  947. if value is _missing and config.allow_population_by_field_name and field.alt_alias:
  948. value = input_data.get(field.name, _missing)
  949. using_name = True
  950. if value is _missing:
  951. if field.required:
  952. errors.append(ErrorWrapper(MissingError(), loc=field.alias))
  953. continue
  954. value = field.get_default()
  955. if not config.validate_all and not field.validate_always:
  956. values[name] = value
  957. continue
  958. else:
  959. fields_set.add(name)
  960. if check_extra:
  961. names_used.add(field.name if using_name else field.alias)
  962. v_, errors_ = field.validate(value, values, loc=field.alias, cls=cls_)
  963. if isinstance(errors_, ErrorWrapper):
  964. errors.append(errors_)
  965. elif isinstance(errors_, list):
  966. errors.extend(errors_)
  967. else:
  968. values[name] = v_
  969. if check_extra:
  970. if isinstance(input_data, GetterDict):
  971. extra = input_data.extra_keys() - names_used
  972. else:
  973. extra = input_data.keys() - names_used
  974. if extra:
  975. fields_set |= extra
  976. if config.extra is Extra.allow:
  977. for f in extra:
  978. values[f] = input_data[f]
  979. else:
  980. for f in sorted(extra):
  981. errors.append(ErrorWrapper(ExtraError(), loc=f))
  982. for skip_on_failure, validator in model.__post_root_validators__:
  983. if skip_on_failure and errors:
  984. continue
  985. try:
  986. values = validator(cls_, values)
  987. except (ValueError, TypeError, AssertionError) as exc:
  988. errors.append(ErrorWrapper(exc, loc=ROOT_KEY))
  989. if errors:
  990. return values, fields_set, ValidationError(errors, cls_)
  991. else:
  992. return values, fields_set, None