main.py 43 KB

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