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.
 
 
 
 

1254 rader
50 KiB

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