Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

1215 rader
47 KiB

  1. from collections import Counter as CollectionCounter, defaultdict, deque
  2. from collections.abc import Hashable as CollectionsHashable, Iterable as CollectionsIterable
  3. from typing import (
  4. TYPE_CHECKING,
  5. Any,
  6. Counter,
  7. DefaultDict,
  8. Deque,
  9. Dict,
  10. FrozenSet,
  11. Generator,
  12. Iterable,
  13. Iterator,
  14. List,
  15. Mapping,
  16. Optional,
  17. Pattern,
  18. Sequence,
  19. Set,
  20. Tuple,
  21. Type,
  22. TypeVar,
  23. Union,
  24. )
  25. from typing_extensions import Annotated
  26. from . import errors as errors_
  27. from .class_validators import Validator, make_generic_validator, prep_validators
  28. from .error_wrappers import ErrorWrapper
  29. from .errors import ConfigError, InvalidDiscriminator, MissingDiscriminator, NoneIsNotAllowedError
  30. from .types import Json, JsonWrapper
  31. from .typing import (
  32. Callable,
  33. ForwardRef,
  34. NoArgAnyCallable,
  35. display_as_type,
  36. get_args,
  37. get_origin,
  38. is_literal_type,
  39. is_new_type,
  40. is_none_type,
  41. is_typeddict,
  42. is_union,
  43. new_type_supertype,
  44. )
  45. from .utils import (
  46. PyObjectStr,
  47. Representation,
  48. ValueItems,
  49. get_discriminator_alias_and_values,
  50. get_unique_discriminator_alias,
  51. lenient_isinstance,
  52. lenient_issubclass,
  53. sequence_like,
  54. smart_deepcopy,
  55. )
  56. from .validators import constant_validator, dict_validator, find_validators, validate_json
  57. Required: Any = Ellipsis
  58. T = TypeVar('T')
  59. class UndefinedType:
  60. def __repr__(self) -> str:
  61. return 'PydanticUndefined'
  62. def __copy__(self: T) -> T:
  63. return self
  64. def __reduce__(self) -> str:
  65. return 'Undefined'
  66. def __deepcopy__(self: T, _: Any) -> T:
  67. return self
  68. Undefined = UndefinedType()
  69. if TYPE_CHECKING:
  70. from .class_validators import ValidatorsList
  71. from .config import BaseConfig
  72. from .error_wrappers import ErrorList
  73. from .types import ModelOrDc
  74. from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs
  75. ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]]
  76. LocStr = Union[Tuple[Union[int, str], ...], str]
  77. BoolUndefined = Union[bool, UndefinedType]
  78. class FieldInfo(Representation):
  79. """
  80. Captures extra information about a field.
  81. """
  82. __slots__ = (
  83. 'default',
  84. 'default_factory',
  85. 'alias',
  86. 'alias_priority',
  87. 'title',
  88. 'description',
  89. 'exclude',
  90. 'include',
  91. 'const',
  92. 'gt',
  93. 'ge',
  94. 'lt',
  95. 'le',
  96. 'multiple_of',
  97. 'max_digits',
  98. 'decimal_places',
  99. 'min_items',
  100. 'max_items',
  101. 'unique_items',
  102. 'min_length',
  103. 'max_length',
  104. 'allow_mutation',
  105. 'repr',
  106. 'regex',
  107. 'discriminator',
  108. 'extra',
  109. )
  110. # field constraints with the default value, it's also used in update_from_config below
  111. __field_constraints__ = {
  112. 'min_length': None,
  113. 'max_length': None,
  114. 'regex': None,
  115. 'gt': None,
  116. 'lt': None,
  117. 'ge': None,
  118. 'le': None,
  119. 'multiple_of': None,
  120. 'max_digits': None,
  121. 'decimal_places': None,
  122. 'min_items': None,
  123. 'max_items': None,
  124. 'unique_items': None,
  125. 'allow_mutation': True,
  126. }
  127. def __init__(self, default: Any = Undefined, **kwargs: Any) -> None:
  128. self.default = default
  129. self.default_factory = kwargs.pop('default_factory', None)
  130. self.alias = kwargs.pop('alias', None)
  131. self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias else None)
  132. self.title = kwargs.pop('title', None)
  133. self.description = kwargs.pop('description', None)
  134. self.exclude = kwargs.pop('exclude', None)
  135. self.include = kwargs.pop('include', None)
  136. self.const = kwargs.pop('const', None)
  137. self.gt = kwargs.pop('gt', None)
  138. self.ge = kwargs.pop('ge', None)
  139. self.lt = kwargs.pop('lt', None)
  140. self.le = kwargs.pop('le', None)
  141. self.multiple_of = kwargs.pop('multiple_of', None)
  142. self.max_digits = kwargs.pop('max_digits', None)
  143. self.decimal_places = kwargs.pop('decimal_places', None)
  144. self.min_items = kwargs.pop('min_items', None)
  145. self.max_items = kwargs.pop('max_items', None)
  146. self.unique_items = kwargs.pop('unique_items', None)
  147. self.min_length = kwargs.pop('min_length', None)
  148. self.max_length = kwargs.pop('max_length', None)
  149. self.allow_mutation = kwargs.pop('allow_mutation', True)
  150. self.regex = kwargs.pop('regex', None)
  151. self.discriminator = kwargs.pop('discriminator', None)
  152. self.repr = kwargs.pop('repr', True)
  153. self.extra = kwargs
  154. def __repr_args__(self) -> 'ReprArgs':
  155. field_defaults_to_hide: Dict[str, Any] = {
  156. 'repr': True,
  157. **self.__field_constraints__,
  158. }
  159. attrs = ((s, getattr(self, s)) for s in self.__slots__)
  160. return [(a, v) for a, v in attrs if v != field_defaults_to_hide.get(a, None)]
  161. def get_constraints(self) -> Set[str]:
  162. """
  163. Gets the constraints set on the field by comparing the constraint value with its default value
  164. :return: the constraints set on field_info
  165. """
  166. return {attr for attr, default in self.__field_constraints__.items() if getattr(self, attr) != default}
  167. def update_from_config(self, from_config: Dict[str, Any]) -> None:
  168. """
  169. Update this FieldInfo based on a dict from get_field_info, only fields which have not been set are dated.
  170. """
  171. for attr_name, value in from_config.items():
  172. try:
  173. current_value = getattr(self, attr_name)
  174. except AttributeError:
  175. # attr_name is not an attribute of FieldInfo, it should therefore be added to extra
  176. self.extra[attr_name] = value
  177. else:
  178. if current_value is self.__field_constraints__.get(attr_name, None):
  179. setattr(self, attr_name, value)
  180. elif attr_name == 'exclude':
  181. self.exclude = ValueItems.merge(value, current_value)
  182. elif attr_name == 'include':
  183. self.include = ValueItems.merge(value, current_value, intersect=True)
  184. def _validate(self) -> None:
  185. if self.default is not Undefined and self.default_factory is not None:
  186. raise ValueError('cannot specify both default and default_factory')
  187. def Field(
  188. default: Any = Undefined,
  189. *,
  190. default_factory: Optional[NoArgAnyCallable] = None,
  191. alias: str = None,
  192. title: str = None,
  193. description: str = None,
  194. exclude: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None,
  195. include: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None,
  196. const: bool = None,
  197. gt: float = None,
  198. ge: float = None,
  199. lt: float = None,
  200. le: float = None,
  201. multiple_of: float = None,
  202. max_digits: int = None,
  203. decimal_places: int = None,
  204. min_items: int = None,
  205. max_items: int = None,
  206. unique_items: bool = None,
  207. min_length: int = None,
  208. max_length: int = None,
  209. allow_mutation: bool = True,
  210. regex: str = None,
  211. discriminator: str = None,
  212. repr: bool = True,
  213. **extra: Any,
  214. ) -> Any:
  215. """
  216. Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
  217. apply only to number fields (``int``, ``float``, ``Decimal``) and some apply only to ``str``.
  218. :param default: since this is replacing the field’s default, its first argument is used
  219. to set the default, use ellipsis (``...``) to indicate the field is required
  220. :param default_factory: callable that will be called when a default value is needed for this field
  221. If both `default` and `default_factory` are set, an error is raised.
  222. :param alias: the public name of the field
  223. :param title: can be any string, used in the schema
  224. :param description: can be any string, used in the schema
  225. :param exclude: exclude this field while dumping.
  226. Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method.
  227. :param include: include this field while dumping.
  228. Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method.
  229. :param const: this field is required and *must* take it's default value
  230. :param gt: only applies to numbers, requires the field to be "greater than". The schema
  231. will have an ``exclusiveMinimum`` validation keyword
  232. :param ge: only applies to numbers, requires the field to be "greater than or equal to". The
  233. schema will have a ``minimum`` validation keyword
  234. :param lt: only applies to numbers, requires the field to be "less than". The schema
  235. will have an ``exclusiveMaximum`` validation keyword
  236. :param le: only applies to numbers, requires the field to be "less than or equal to". The
  237. schema will have a ``maximum`` validation keyword
  238. :param multiple_of: only applies to numbers, requires the field to be "a multiple of". The
  239. schema will have a ``multipleOf`` validation keyword
  240. :param max_digits: only applies to Decimals, requires the field to have a maximum number
  241. of digits within the decimal. It does not include a zero before the decimal point or trailing decimal zeroes.
  242. :param decimal_places: only applies to Decimals, requires the field to have at most a number of decimal places
  243. allowed. It does not include trailing decimal zeroes.
  244. :param min_items: only applies to lists, requires the field to have a minimum number of
  245. elements. The schema will have a ``minItems`` validation keyword
  246. :param max_items: only applies to lists, requires the field to have a maximum number of
  247. elements. The schema will have a ``maxItems`` validation keyword
  248. :param max_items: only applies to lists, requires the field not to have duplicated
  249. elements. The schema will have a ``uniqueItems`` validation keyword
  250. :param min_length: only applies to strings, requires the field to have a minimum length. The
  251. schema will have a ``maximum`` validation keyword
  252. :param max_length: only applies to strings, requires the field to have a maximum length. The
  253. schema will have a ``maxLength`` validation keyword
  254. :param allow_mutation: a boolean which defaults to True. When False, the field raises a TypeError if the field is
  255. assigned on an instance. The BaseModel Config must set validate_assignment to True
  256. :param regex: only applies to strings, requires the field match against a regular expression
  257. pattern string. The schema will have a ``pattern`` validation keyword
  258. :param discriminator: only useful with a (discriminated a.k.a. tagged) `Union` of sub models with a common field.
  259. The `discriminator` is the name of this common field to shorten validation and improve generated schema
  260. :param repr: show this field in the representation
  261. :param **extra: any additional keyword arguments will be added as is to the schema
  262. """
  263. field_info = FieldInfo(
  264. default,
  265. default_factory=default_factory,
  266. alias=alias,
  267. title=title,
  268. description=description,
  269. exclude=exclude,
  270. include=include,
  271. const=const,
  272. gt=gt,
  273. ge=ge,
  274. lt=lt,
  275. le=le,
  276. multiple_of=multiple_of,
  277. max_digits=max_digits,
  278. decimal_places=decimal_places,
  279. min_items=min_items,
  280. max_items=max_items,
  281. unique_items=unique_items,
  282. min_length=min_length,
  283. max_length=max_length,
  284. allow_mutation=allow_mutation,
  285. regex=regex,
  286. discriminator=discriminator,
  287. repr=repr,
  288. **extra,
  289. )
  290. field_info._validate()
  291. return field_info
  292. # used to be an enum but changed to int's for small performance improvement as less access overhead
  293. SHAPE_SINGLETON = 1
  294. SHAPE_LIST = 2
  295. SHAPE_SET = 3
  296. SHAPE_MAPPING = 4
  297. SHAPE_TUPLE = 5
  298. SHAPE_TUPLE_ELLIPSIS = 6
  299. SHAPE_SEQUENCE = 7
  300. SHAPE_FROZENSET = 8
  301. SHAPE_ITERABLE = 9
  302. SHAPE_GENERIC = 10
  303. SHAPE_DEQUE = 11
  304. SHAPE_DICT = 12
  305. SHAPE_DEFAULTDICT = 13
  306. SHAPE_COUNTER = 14
  307. SHAPE_NAME_LOOKUP = {
  308. SHAPE_LIST: 'List[{}]',
  309. SHAPE_SET: 'Set[{}]',
  310. SHAPE_TUPLE_ELLIPSIS: 'Tuple[{}, ...]',
  311. SHAPE_SEQUENCE: 'Sequence[{}]',
  312. SHAPE_FROZENSET: 'FrozenSet[{}]',
  313. SHAPE_ITERABLE: 'Iterable[{}]',
  314. SHAPE_DEQUE: 'Deque[{}]',
  315. SHAPE_DICT: 'Dict[{}]',
  316. SHAPE_DEFAULTDICT: 'DefaultDict[{}]',
  317. SHAPE_COUNTER: 'Counter[{}]',
  318. }
  319. MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING, SHAPE_COUNTER}
  320. class ModelField(Representation):
  321. __slots__ = (
  322. 'type_',
  323. 'outer_type_',
  324. 'sub_fields',
  325. 'sub_fields_mapping',
  326. 'key_field',
  327. 'validators',
  328. 'pre_validators',
  329. 'post_validators',
  330. 'default',
  331. 'default_factory',
  332. 'required',
  333. 'model_config',
  334. 'name',
  335. 'alias',
  336. 'has_alias',
  337. 'field_info',
  338. 'discriminator_key',
  339. 'discriminator_alias',
  340. 'validate_always',
  341. 'allow_none',
  342. 'shape',
  343. 'class_validators',
  344. 'parse_json',
  345. )
  346. def __init__(
  347. self,
  348. *,
  349. name: str,
  350. type_: Type[Any],
  351. class_validators: Optional[Dict[str, Validator]],
  352. model_config: Type['BaseConfig'],
  353. default: Any = None,
  354. default_factory: Optional[NoArgAnyCallable] = None,
  355. required: 'BoolUndefined' = Undefined,
  356. alias: str = None,
  357. field_info: Optional[FieldInfo] = None,
  358. ) -> None:
  359. self.name: str = name
  360. self.has_alias: bool = bool(alias)
  361. self.alias: str = alias or name
  362. self.type_: Any = type_
  363. self.outer_type_: Any = type_
  364. self.class_validators = class_validators or {}
  365. self.default: Any = default
  366. self.default_factory: Optional[NoArgAnyCallable] = default_factory
  367. self.required: 'BoolUndefined' = required
  368. self.model_config = model_config
  369. self.field_info: FieldInfo = field_info or FieldInfo(default)
  370. self.discriminator_key: Optional[str] = self.field_info.discriminator
  371. self.discriminator_alias: Optional[str] = self.discriminator_key
  372. self.allow_none: bool = False
  373. self.validate_always: bool = False
  374. self.sub_fields: Optional[List[ModelField]] = None
  375. self.sub_fields_mapping: Optional[Dict[str, 'ModelField']] = None # used for discriminated union
  376. self.key_field: Optional[ModelField] = None
  377. self.validators: 'ValidatorsList' = []
  378. self.pre_validators: Optional['ValidatorsList'] = None
  379. self.post_validators: Optional['ValidatorsList'] = None
  380. self.parse_json: bool = False
  381. self.shape: int = SHAPE_SINGLETON
  382. self.model_config.prepare_field(self)
  383. self.prepare()
  384. def get_default(self) -> Any:
  385. return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()
  386. @staticmethod
  387. def _get_field_info(
  388. field_name: str, annotation: Any, value: Any, config: Type['BaseConfig']
  389. ) -> Tuple[FieldInfo, Any]:
  390. """
  391. Get a FieldInfo from a root typing.Annotated annotation, value, or config default.
  392. The FieldInfo may be set in typing.Annotated or the value, but not both. If neither contain
  393. a FieldInfo, a new one will be created using the config.
  394. :param field_name: name of the field for use in error messages
  395. :param annotation: a type hint such as `str` or `Annotated[str, Field(..., min_length=5)]`
  396. :param value: the field's assigned value
  397. :param config: the model's config object
  398. :return: the FieldInfo contained in the `annotation`, the value, or a new one from the config.
  399. """
  400. field_info_from_config = config.get_field_info(field_name)
  401. field_info = None
  402. if get_origin(annotation) is Annotated:
  403. field_infos = [arg for arg in get_args(annotation)[1:] if isinstance(arg, FieldInfo)]
  404. if len(field_infos) > 1:
  405. raise ValueError(f'cannot specify multiple `Annotated` `Field`s for {field_name!r}')
  406. field_info = next(iter(field_infos), None)
  407. if field_info is not None:
  408. field_info.update_from_config(field_info_from_config)
  409. if field_info.default is not Undefined:
  410. raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}')
  411. if value is not Undefined and value is not Required:
  412. # check also `Required` because of `validate_arguments` that sets `...` as default value
  413. field_info.default = value
  414. if isinstance(value, FieldInfo):
  415. if field_info is not None:
  416. raise ValueError(f'cannot specify `Annotated` and value `Field`s together for {field_name!r}')
  417. field_info = value
  418. field_info.update_from_config(field_info_from_config)
  419. elif field_info is None:
  420. field_info = FieldInfo(value, **field_info_from_config)
  421. value = None if field_info.default_factory is not None else field_info.default
  422. field_info._validate()
  423. return field_info, value
  424. @classmethod
  425. def infer(
  426. cls,
  427. *,
  428. name: str,
  429. value: Any,
  430. annotation: Any,
  431. class_validators: Optional[Dict[str, Validator]],
  432. config: Type['BaseConfig'],
  433. ) -> 'ModelField':
  434. from .schema import get_annotation_from_field_info
  435. field_info, value = cls._get_field_info(name, annotation, value, config)
  436. required: 'BoolUndefined' = Undefined
  437. if value is Required:
  438. required = True
  439. value = None
  440. elif value is not Undefined:
  441. required = False
  442. annotation = get_annotation_from_field_info(annotation, field_info, name, config.validate_assignment)
  443. return cls(
  444. name=name,
  445. type_=annotation,
  446. alias=field_info.alias,
  447. class_validators=class_validators,
  448. default=value,
  449. default_factory=field_info.default_factory,
  450. required=required,
  451. model_config=config,
  452. field_info=field_info,
  453. )
  454. def set_config(self, config: Type['BaseConfig']) -> None:
  455. self.model_config = config
  456. info_from_config = config.get_field_info(self.name)
  457. config.prepare_field(self)
  458. new_alias = info_from_config.get('alias')
  459. new_alias_priority = info_from_config.get('alias_priority') or 0
  460. if new_alias and new_alias_priority >= (self.field_info.alias_priority or 0):
  461. self.field_info.alias = new_alias
  462. self.field_info.alias_priority = new_alias_priority
  463. self.alias = new_alias
  464. new_exclude = info_from_config.get('exclude')
  465. if new_exclude is not None:
  466. self.field_info.exclude = ValueItems.merge(self.field_info.exclude, new_exclude)
  467. new_include = info_from_config.get('include')
  468. if new_include is not None:
  469. self.field_info.include = ValueItems.merge(self.field_info.include, new_include, intersect=True)
  470. @property
  471. def alt_alias(self) -> bool:
  472. return self.name != self.alias
  473. def prepare(self) -> None:
  474. """
  475. Prepare the field but inspecting self.default, self.type_ etc.
  476. Note: this method is **not** idempotent (because _type_analysis is not idempotent),
  477. e.g. calling it it multiple times may modify the field and configure it incorrectly.
  478. """
  479. self._set_default_and_type()
  480. if self.type_.__class__ is ForwardRef or self.type_.__class__ is DeferredType:
  481. # self.type_ is currently a ForwardRef and there's nothing we can do now,
  482. # user will need to call model.update_forward_refs()
  483. return
  484. self._type_analysis()
  485. if self.required is Undefined:
  486. self.required = True
  487. if self.default is Undefined and self.default_factory is None:
  488. self.default = None
  489. self.populate_validators()
  490. def _set_default_and_type(self) -> None:
  491. """
  492. Set the default value, infer the type if needed and check if `None` value is valid.
  493. """
  494. if self.default_factory is not None:
  495. if self.type_ is Undefined:
  496. raise errors_.ConfigError(
  497. f'you need to set the type of field {self.name!r} when using `default_factory`'
  498. )
  499. return
  500. default_value = self.get_default()
  501. if default_value is not None and self.type_ is Undefined:
  502. self.type_ = default_value.__class__
  503. self.outer_type_ = self.type_
  504. if self.type_ is Undefined:
  505. raise errors_.ConfigError(f'unable to infer type for attribute "{self.name}"')
  506. if self.required is False and default_value is None:
  507. self.allow_none = True
  508. def _type_analysis(self) -> None: # noqa: C901 (ignore complexity)
  509. # typing interface is horrible, we have to do some ugly checks
  510. if lenient_issubclass(self.type_, JsonWrapper):
  511. self.type_ = self.type_.inner_type
  512. self.parse_json = True
  513. elif lenient_issubclass(self.type_, Json):
  514. self.type_ = Any
  515. self.parse_json = True
  516. elif isinstance(self.type_, TypeVar):
  517. if self.type_.__bound__:
  518. self.type_ = self.type_.__bound__
  519. elif self.type_.__constraints__:
  520. self.type_ = Union[self.type_.__constraints__]
  521. else:
  522. self.type_ = Any
  523. elif is_new_type(self.type_):
  524. self.type_ = new_type_supertype(self.type_)
  525. if self.type_ is Any or self.type_ is object:
  526. if self.required is Undefined:
  527. self.required = False
  528. self.allow_none = True
  529. return
  530. elif self.type_ is Pattern:
  531. # python 3.7 only, Pattern is a typing object but without sub fields
  532. return
  533. elif is_literal_type(self.type_):
  534. return
  535. elif is_typeddict(self.type_):
  536. return
  537. origin = get_origin(self.type_)
  538. if origin is Annotated:
  539. self.type_ = get_args(self.type_)[0]
  540. self._type_analysis()
  541. return
  542. if self.discriminator_key is not None and not is_union(origin):
  543. raise TypeError('`discriminator` can only be used with `Union` type')
  544. # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None`
  545. if origin is None or origin is CollectionsHashable:
  546. # field is not "typing" object eg. Union, Dict, List etc.
  547. # allow None for virtual superclasses of NoneType, e.g. Hashable
  548. if isinstance(self.type_, type) and isinstance(None, self.type_):
  549. self.allow_none = True
  550. return
  551. elif origin is Callable:
  552. return
  553. elif is_union(origin):
  554. types_ = []
  555. for type_ in get_args(self.type_):
  556. if is_none_type(type_) or type_ is Any or type_ is object:
  557. if self.required is Undefined:
  558. self.required = False
  559. self.allow_none = True
  560. if is_none_type(type_):
  561. continue
  562. types_.append(type_)
  563. if len(types_) == 1:
  564. # Optional[]
  565. self.type_ = types_[0]
  566. # this is the one case where the "outer type" isn't just the original type
  567. self.outer_type_ = self.type_
  568. # re-run to correctly interpret the new self.type_
  569. self._type_analysis()
  570. else:
  571. self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_]
  572. if self.discriminator_key is not None:
  573. self.prepare_discriminated_union_sub_fields()
  574. return
  575. elif issubclass(origin, Tuple): # type: ignore
  576. # origin == Tuple without item type
  577. args = get_args(self.type_)
  578. if not args: # plain tuple
  579. self.type_ = Any
  580. self.shape = SHAPE_TUPLE_ELLIPSIS
  581. elif len(args) == 2 and args[1] is Ellipsis: # e.g. Tuple[int, ...]
  582. self.type_ = args[0]
  583. self.shape = SHAPE_TUPLE_ELLIPSIS
  584. self.sub_fields = [self._create_sub_type(args[0], f'{self.name}_0')]
  585. elif args == ((),): # Tuple[()] means empty tuple
  586. self.shape = SHAPE_TUPLE
  587. self.type_ = Any
  588. self.sub_fields = []
  589. else:
  590. self.shape = SHAPE_TUPLE
  591. self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(args)]
  592. return
  593. elif issubclass(origin, List):
  594. # Create self validators
  595. get_validators = getattr(self.type_, '__get_validators__', None)
  596. if get_validators:
  597. self.class_validators.update(
  598. {f'list_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())}
  599. )
  600. self.type_ = get_args(self.type_)[0]
  601. self.shape = SHAPE_LIST
  602. elif issubclass(origin, Set):
  603. # Create self validators
  604. get_validators = getattr(self.type_, '__get_validators__', None)
  605. if get_validators:
  606. self.class_validators.update(
  607. {f'set_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())}
  608. )
  609. self.type_ = get_args(self.type_)[0]
  610. self.shape = SHAPE_SET
  611. elif issubclass(origin, FrozenSet):
  612. # Create self validators
  613. get_validators = getattr(self.type_, '__get_validators__', None)
  614. if get_validators:
  615. self.class_validators.update(
  616. {f'frozenset_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())}
  617. )
  618. self.type_ = get_args(self.type_)[0]
  619. self.shape = SHAPE_FROZENSET
  620. elif issubclass(origin, Deque):
  621. self.type_ = get_args(self.type_)[0]
  622. self.shape = SHAPE_DEQUE
  623. elif issubclass(origin, Sequence):
  624. self.type_ = get_args(self.type_)[0]
  625. self.shape = SHAPE_SEQUENCE
  626. # priority to most common mapping: dict
  627. elif origin is dict or origin is Dict:
  628. self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
  629. self.type_ = get_args(self.type_)[1]
  630. self.shape = SHAPE_DICT
  631. elif issubclass(origin, DefaultDict):
  632. self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
  633. self.type_ = get_args(self.type_)[1]
  634. self.shape = SHAPE_DEFAULTDICT
  635. elif issubclass(origin, Counter):
  636. self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
  637. self.type_ = int
  638. self.shape = SHAPE_COUNTER
  639. elif issubclass(origin, Mapping):
  640. self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
  641. self.type_ = get_args(self.type_)[1]
  642. self.shape = SHAPE_MAPPING
  643. # Equality check as almost everything inherits form Iterable, including str
  644. # check for Iterable and CollectionsIterable, as it could receive one even when declared with the other
  645. elif origin in {Iterable, CollectionsIterable}:
  646. self.type_ = get_args(self.type_)[0]
  647. self.shape = SHAPE_ITERABLE
  648. self.sub_fields = [self._create_sub_type(self.type_, f'{self.name}_type')]
  649. elif issubclass(origin, Type): # type: ignore
  650. return
  651. elif hasattr(origin, '__get_validators__') or self.model_config.arbitrary_types_allowed:
  652. # Is a Pydantic-compatible generic that handles itself
  653. # or we have arbitrary_types_allowed = True
  654. self.shape = SHAPE_GENERIC
  655. self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(get_args(self.type_))]
  656. self.type_ = origin
  657. return
  658. else:
  659. raise TypeError(f'Fields of type "{origin}" are not supported.')
  660. # type_ has been refined eg. as the type of a List and sub_fields needs to be populated
  661. self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)]
  662. def prepare_discriminated_union_sub_fields(self) -> None:
  663. """
  664. Prepare the mapping <discriminator key> -> <ModelField> and update `sub_fields`
  665. Note that this process can be aborted if a `ForwardRef` is encountered
  666. """
  667. assert self.discriminator_key is not None
  668. if self.type_.__class__ is DeferredType:
  669. return
  670. assert self.sub_fields is not None
  671. sub_fields_mapping: Dict[str, 'ModelField'] = {}
  672. all_aliases: Set[str] = set()
  673. for sub_field in self.sub_fields:
  674. t = sub_field.type_
  675. if t.__class__ is ForwardRef:
  676. # Stopping everything...will need to call `update_forward_refs`
  677. return
  678. alias, discriminator_values = get_discriminator_alias_and_values(t, self.discriminator_key)
  679. all_aliases.add(alias)
  680. for discriminator_value in discriminator_values:
  681. sub_fields_mapping[discriminator_value] = sub_field
  682. self.sub_fields_mapping = sub_fields_mapping
  683. self.discriminator_alias = get_unique_discriminator_alias(all_aliases, self.discriminator_key)
  684. def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField':
  685. if for_keys:
  686. class_validators = None
  687. else:
  688. # validators for sub items should not have `each_item` as we want to check only the first sublevel
  689. class_validators = {
  690. k: Validator(
  691. func=v.func,
  692. pre=v.pre,
  693. each_item=False,
  694. always=v.always,
  695. check_fields=v.check_fields,
  696. skip_on_failure=v.skip_on_failure,
  697. )
  698. for k, v in self.class_validators.items()
  699. if v.each_item
  700. }
  701. field_info, _ = self._get_field_info(name, type_, None, self.model_config)
  702. return self.__class__(
  703. type_=type_,
  704. name=name,
  705. class_validators=class_validators,
  706. model_config=self.model_config,
  707. field_info=field_info,
  708. )
  709. def populate_validators(self) -> None:
  710. """
  711. Prepare self.pre_validators, self.validators, and self.post_validators based on self.type_'s __get_validators__
  712. and class validators. This method should be idempotent, e.g. it should be safe to call multiple times
  713. without mis-configuring the field.
  714. """
  715. self.validate_always = getattr(self.type_, 'validate_always', False) or any(
  716. v.always for v in self.class_validators.values()
  717. )
  718. class_validators_ = self.class_validators.values()
  719. if not self.sub_fields or self.shape == SHAPE_GENERIC:
  720. get_validators = getattr(self.type_, '__get_validators__', None)
  721. v_funcs = (
  722. *[v.func for v in class_validators_ if v.each_item and v.pre],
  723. *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))),
  724. *[v.func for v in class_validators_ if v.each_item and not v.pre],
  725. )
  726. self.validators = prep_validators(v_funcs)
  727. self.pre_validators = []
  728. self.post_validators = []
  729. if self.field_info and self.field_info.const:
  730. self.post_validators.append(make_generic_validator(constant_validator))
  731. if class_validators_:
  732. self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre)
  733. self.post_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and not v.pre)
  734. if self.parse_json:
  735. self.pre_validators.append(make_generic_validator(validate_json))
  736. self.pre_validators = self.pre_validators or None
  737. self.post_validators = self.post_validators or None
  738. def validate(
  739. self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None
  740. ) -> 'ValidateReturn':
  741. assert self.type_.__class__ is not DeferredType
  742. if self.type_.__class__ is ForwardRef:
  743. assert cls is not None
  744. raise ConfigError(
  745. f'field "{self.name}" not yet prepared so type is still a ForwardRef, '
  746. f'you might need to call {cls.__name__}.update_forward_refs().'
  747. )
  748. errors: Optional['ErrorList']
  749. if self.pre_validators:
  750. v, errors = self._apply_validators(v, values, loc, cls, self.pre_validators)
  751. if errors:
  752. return v, errors
  753. if v is None:
  754. if is_none_type(self.type_):
  755. # keep validating
  756. pass
  757. elif self.allow_none:
  758. if self.post_validators:
  759. return self._apply_validators(v, values, loc, cls, self.post_validators)
  760. else:
  761. return None, None
  762. else:
  763. return v, ErrorWrapper(NoneIsNotAllowedError(), loc)
  764. if self.shape == SHAPE_SINGLETON:
  765. v, errors = self._validate_singleton(v, values, loc, cls)
  766. elif self.shape in MAPPING_LIKE_SHAPES:
  767. v, errors = self._validate_mapping_like(v, values, loc, cls)
  768. elif self.shape == SHAPE_TUPLE:
  769. v, errors = self._validate_tuple(v, values, loc, cls)
  770. elif self.shape == SHAPE_ITERABLE:
  771. v, errors = self._validate_iterable(v, values, loc, cls)
  772. elif self.shape == SHAPE_GENERIC:
  773. v, errors = self._apply_validators(v, values, loc, cls, self.validators)
  774. else:
  775. # sequence, list, set, generator, tuple with ellipsis, frozen set
  776. v, errors = self._validate_sequence_like(v, values, loc, cls)
  777. if not errors and self.post_validators:
  778. v, errors = self._apply_validators(v, values, loc, cls, self.post_validators)
  779. return v, errors
  780. def _validate_sequence_like( # noqa: C901 (ignore complexity)
  781. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
  782. ) -> 'ValidateReturn':
  783. """
  784. Validate sequence-like containers: lists, tuples, sets and generators
  785. Note that large if-else blocks are necessary to enable Cython
  786. optimization, which is why we disable the complexity check above.
  787. """
  788. if not sequence_like(v):
  789. e: errors_.PydanticTypeError
  790. if self.shape == SHAPE_LIST:
  791. e = errors_.ListError()
  792. elif self.shape in (SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS):
  793. e = errors_.TupleError()
  794. elif self.shape == SHAPE_SET:
  795. e = errors_.SetError()
  796. elif self.shape == SHAPE_FROZENSET:
  797. e = errors_.FrozenSetError()
  798. else:
  799. e = errors_.SequenceError()
  800. return v, ErrorWrapper(e, loc)
  801. loc = loc if isinstance(loc, tuple) else (loc,)
  802. result = []
  803. errors: List[ErrorList] = []
  804. for i, v_ in enumerate(v):
  805. v_loc = *loc, i
  806. r, ee = self._validate_singleton(v_, values, v_loc, cls)
  807. if ee:
  808. errors.append(ee)
  809. else:
  810. result.append(r)
  811. if errors:
  812. return v, errors
  813. converted: Union[List[Any], Set[Any], FrozenSet[Any], Tuple[Any, ...], Iterator[Any], Deque[Any]] = result
  814. if self.shape == SHAPE_SET:
  815. converted = set(result)
  816. elif self.shape == SHAPE_FROZENSET:
  817. converted = frozenset(result)
  818. elif self.shape == SHAPE_TUPLE_ELLIPSIS:
  819. converted = tuple(result)
  820. elif self.shape == SHAPE_DEQUE:
  821. converted = deque(result)
  822. elif self.shape == SHAPE_SEQUENCE:
  823. if isinstance(v, tuple):
  824. converted = tuple(result)
  825. elif isinstance(v, set):
  826. converted = set(result)
  827. elif isinstance(v, Generator):
  828. converted = iter(result)
  829. elif isinstance(v, deque):
  830. converted = deque(result)
  831. return converted, None
  832. def _validate_iterable(
  833. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
  834. ) -> 'ValidateReturn':
  835. """
  836. Validate Iterables.
  837. This intentionally doesn't validate values to allow infinite generators.
  838. """
  839. try:
  840. iterable = iter(v)
  841. except TypeError:
  842. return v, ErrorWrapper(errors_.IterableError(), loc)
  843. return iterable, None
  844. def _validate_tuple(
  845. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
  846. ) -> 'ValidateReturn':
  847. e: Optional[Exception] = None
  848. if not sequence_like(v):
  849. e = errors_.TupleError()
  850. else:
  851. actual_length, expected_length = len(v), len(self.sub_fields) # type: ignore
  852. if actual_length != expected_length:
  853. e = errors_.TupleLengthError(actual_length=actual_length, expected_length=expected_length)
  854. if e:
  855. return v, ErrorWrapper(e, loc)
  856. loc = loc if isinstance(loc, tuple) else (loc,)
  857. result = []
  858. errors: List[ErrorList] = []
  859. for i, (v_, field) in enumerate(zip(v, self.sub_fields)): # type: ignore
  860. v_loc = *loc, i
  861. r, ee = field.validate(v_, values, loc=v_loc, cls=cls)
  862. if ee:
  863. errors.append(ee)
  864. else:
  865. result.append(r)
  866. if errors:
  867. return v, errors
  868. else:
  869. return tuple(result), None
  870. def _validate_mapping_like(
  871. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
  872. ) -> 'ValidateReturn':
  873. try:
  874. v_iter = dict_validator(v)
  875. except TypeError as exc:
  876. return v, ErrorWrapper(exc, loc)
  877. loc = loc if isinstance(loc, tuple) else (loc,)
  878. result, errors = {}, []
  879. for k, v_ in v_iter.items():
  880. v_loc = *loc, '__key__'
  881. key_result, key_errors = self.key_field.validate(k, values, loc=v_loc, cls=cls) # type: ignore
  882. if key_errors:
  883. errors.append(key_errors)
  884. continue
  885. v_loc = *loc, k
  886. value_result, value_errors = self._validate_singleton(v_, values, v_loc, cls)
  887. if value_errors:
  888. errors.append(value_errors)
  889. continue
  890. result[key_result] = value_result
  891. if errors:
  892. return v, errors
  893. elif self.shape == SHAPE_DICT:
  894. return result, None
  895. elif self.shape == SHAPE_DEFAULTDICT:
  896. return defaultdict(self.type_, result), None
  897. elif self.shape == SHAPE_COUNTER:
  898. return CollectionCounter(result), None
  899. else:
  900. return self._get_mapping_value(v, result), None
  901. def _get_mapping_value(self, original: T, converted: Dict[Any, Any]) -> Union[T, Dict[Any, Any]]:
  902. """
  903. When type is `Mapping[KT, KV]` (or another unsupported mapping), we try to avoid
  904. coercing to `dict` unwillingly.
  905. """
  906. original_cls = original.__class__
  907. if original_cls == dict or original_cls == Dict:
  908. return converted
  909. elif original_cls in {defaultdict, DefaultDict}:
  910. return defaultdict(self.type_, converted)
  911. else:
  912. try:
  913. # Counter, OrderedDict, UserDict, ...
  914. return original_cls(converted) # type: ignore
  915. except TypeError:
  916. raise RuntimeError(f'Could not convert dictionary to {original_cls.__name__!r}') from None
  917. def _validate_singleton(
  918. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
  919. ) -> 'ValidateReturn':
  920. if self.sub_fields:
  921. if self.discriminator_key is not None:
  922. return self._validate_discriminated_union(v, values, loc, cls)
  923. errors = []
  924. if self.model_config.smart_union and is_union(get_origin(self.type_)):
  925. # 1st pass: check if the value is an exact instance of one of the Union types
  926. # (e.g. to avoid coercing a bool into an int)
  927. for field in self.sub_fields:
  928. if v.__class__ is field.outer_type_:
  929. return v, None
  930. # 2nd pass: check if the value is an instance of any subclass of the Union types
  931. for field in self.sub_fields:
  932. # This whole logic will be improved later on to support more complex `isinstance` checks
  933. # It will probably be done once a strict mode is added and be something like:
  934. # ```
  935. # value, error = field.validate(v, values, strict=True)
  936. # if error is None:
  937. # return value, None
  938. # ```
  939. try:
  940. if isinstance(v, field.outer_type_):
  941. return v, None
  942. except TypeError:
  943. # compound type
  944. if lenient_isinstance(v, get_origin(field.outer_type_)):
  945. value, error = field.validate(v, values, loc=loc, cls=cls)
  946. if not error:
  947. return value, None
  948. # 1st pass by default or 3rd pass with `smart_union` enabled:
  949. # check if the value can be coerced into one of the Union types
  950. for field in self.sub_fields:
  951. value, error = field.validate(v, values, loc=loc, cls=cls)
  952. if error:
  953. errors.append(error)
  954. else:
  955. return value, None
  956. return v, errors
  957. else:
  958. return self._apply_validators(v, values, loc, cls, self.validators)
  959. def _validate_discriminated_union(
  960. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
  961. ) -> 'ValidateReturn':
  962. assert self.discriminator_key is not None
  963. assert self.discriminator_alias is not None
  964. try:
  965. discriminator_value = v[self.discriminator_alias]
  966. except KeyError:
  967. return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc)
  968. except TypeError:
  969. try:
  970. # BaseModel or dataclass
  971. discriminator_value = getattr(v, self.discriminator_alias)
  972. except (AttributeError, TypeError):
  973. return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc)
  974. try:
  975. sub_field = self.sub_fields_mapping[discriminator_value] # type: ignore[index]
  976. except TypeError:
  977. assert cls is not None
  978. raise ConfigError(
  979. f'field "{self.name}" not yet prepared so type is still a ForwardRef, '
  980. f'you might need to call {cls.__name__}.update_forward_refs().'
  981. )
  982. except KeyError:
  983. assert self.sub_fields_mapping is not None
  984. return v, ErrorWrapper(
  985. InvalidDiscriminator(
  986. discriminator_key=self.discriminator_key,
  987. discriminator_value=discriminator_value,
  988. allowed_values=list(self.sub_fields_mapping),
  989. ),
  990. loc,
  991. )
  992. else:
  993. if not isinstance(loc, tuple):
  994. loc = (loc,)
  995. return sub_field.validate(v, values, loc=(*loc, display_as_type(sub_field.type_)), cls=cls)
  996. def _apply_validators(
  997. self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'], validators: 'ValidatorsList'
  998. ) -> 'ValidateReturn':
  999. for validator in validators:
  1000. try:
  1001. v = validator(cls, v, values, self, self.model_config)
  1002. except (ValueError, TypeError, AssertionError) as exc:
  1003. return v, ErrorWrapper(exc, loc)
  1004. return v, None
  1005. def is_complex(self) -> bool:
  1006. """
  1007. Whether the field is "complex" eg. env variables should be parsed as JSON.
  1008. """
  1009. from .main import BaseModel
  1010. return (
  1011. self.shape != SHAPE_SINGLETON
  1012. or lenient_issubclass(self.type_, (BaseModel, list, set, frozenset, dict))
  1013. or hasattr(self.type_, '__pydantic_model__') # pydantic dataclass
  1014. )
  1015. def _type_display(self) -> PyObjectStr:
  1016. t = display_as_type(self.type_)
  1017. # have to do this since display_as_type(self.outer_type_) is different (and wrong) on python 3.6
  1018. if self.shape in MAPPING_LIKE_SHAPES:
  1019. t = f'Mapping[{display_as_type(self.key_field.type_)}, {t}]' # type: ignore
  1020. elif self.shape == SHAPE_TUPLE:
  1021. t = 'Tuple[{}]'.format(', '.join(display_as_type(f.type_) for f in self.sub_fields)) # type: ignore
  1022. elif self.shape == SHAPE_GENERIC:
  1023. assert self.sub_fields
  1024. t = '{}[{}]'.format(
  1025. display_as_type(self.type_), ', '.join(display_as_type(f.type_) for f in self.sub_fields)
  1026. )
  1027. elif self.shape != SHAPE_SINGLETON:
  1028. t = SHAPE_NAME_LOOKUP[self.shape].format(t)
  1029. if self.allow_none and (self.shape != SHAPE_SINGLETON or not self.sub_fields):
  1030. t = f'Optional[{t}]'
  1031. return PyObjectStr(t)
  1032. def __repr_args__(self) -> 'ReprArgs':
  1033. args = [('name', self.name), ('type', self._type_display()), ('required', self.required)]
  1034. if not self.required:
  1035. if self.default_factory is not None:
  1036. args.append(('default_factory', f'<function {self.default_factory.__name__}>'))
  1037. else:
  1038. args.append(('default', self.default))
  1039. if self.alt_alias:
  1040. args.append(('alias', self.alias))
  1041. return args
  1042. class ModelPrivateAttr(Representation):
  1043. __slots__ = ('default', 'default_factory')
  1044. def __init__(self, default: Any = Undefined, *, default_factory: Optional[NoArgAnyCallable] = None) -> None:
  1045. self.default = default
  1046. self.default_factory = default_factory
  1047. def get_default(self) -> Any:
  1048. return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()
  1049. def __eq__(self, other: Any) -> bool:
  1050. return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
  1051. other.default,
  1052. other.default_factory,
  1053. )
  1054. def PrivateAttr(
  1055. default: Any = Undefined,
  1056. *,
  1057. default_factory: Optional[NoArgAnyCallable] = None,
  1058. ) -> Any:
  1059. """
  1060. Indicates that attribute is only used internally and never mixed with regular fields.
  1061. Types or values of private attrs are not checked by pydantic and it's up to you to keep them relevant.
  1062. Private attrs are stored in model __slots__.
  1063. :param default: the attribute’s default value
  1064. :param default_factory: callable that will be called when a default value is needed for this attribute
  1065. If both `default` and `default_factory` are set, an error is raised.
  1066. """
  1067. if default is not Undefined and default_factory is not None:
  1068. raise ValueError('cannot specify both default and default_factory')
  1069. return ModelPrivateAttr(
  1070. default,
  1071. default_factory=default_factory,
  1072. )
  1073. class DeferredType:
  1074. """
  1075. Used to postpone field preparation, while creating recursive generic models.
  1076. """