fields.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. """Defining fields on models."""
  2. from __future__ import annotations as _annotations
  3. import dataclasses
  4. import inspect
  5. import re
  6. import sys
  7. from collections.abc import Callable, Mapping
  8. from copy import copy
  9. from dataclasses import Field as DataclassField
  10. from functools import cached_property
  11. from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, TypeVar, cast, final, overload
  12. from warnings import warn
  13. import annotated_types
  14. import typing_extensions
  15. from pydantic_core import MISSING, PydanticUndefined
  16. from typing_extensions import Self, TypeAlias, TypedDict, Unpack, deprecated
  17. from typing_inspection import typing_objects
  18. from typing_inspection.introspection import UNKNOWN, AnnotationSource, ForbiddenQualifier, Qualifier, inspect_annotation
  19. from . import types
  20. from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils
  21. from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace
  22. from .aliases import AliasChoices, AliasGenerator, AliasPath
  23. from .config import JsonDict
  24. from .errors import PydanticForbiddenQualifier, PydanticUserError
  25. from .json_schema import PydanticJsonSchemaWarning
  26. from .warnings import PydanticDeprecatedSince20
  27. if TYPE_CHECKING:
  28. from ._internal._config import ConfigWrapper
  29. from ._internal._repr import ReprArgs
  30. __all__ = 'Field', 'FieldInfo', 'PrivateAttr', 'computed_field'
  31. _Unset: Any = PydanticUndefined
  32. if sys.version_info >= (3, 13):
  33. import warnings
  34. Deprecated: TypeAlias = warnings.deprecated | deprecated
  35. else:
  36. Deprecated: TypeAlias = deprecated
  37. class _FromFieldInfoInputs(TypedDict, total=False):
  38. """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
  39. # TODO PEP 747: use TypeForm:
  40. annotation: type[Any] | None
  41. default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
  42. alias: str | None
  43. alias_priority: int | None
  44. validation_alias: str | AliasPath | AliasChoices | None
  45. serialization_alias: str | None
  46. title: str | None
  47. field_title_generator: Callable[[str, FieldInfo], str] | None
  48. description: str | None
  49. examples: list[Any] | None
  50. exclude: bool | None
  51. exclude_if: Callable[[Any], bool] | None
  52. gt: annotated_types.SupportsGt | None
  53. ge: annotated_types.SupportsGe | None
  54. lt: annotated_types.SupportsLt | None
  55. le: annotated_types.SupportsLe | None
  56. multiple_of: float | None
  57. strict: bool | None
  58. min_length: int | None
  59. max_length: int | None
  60. pattern: str | re.Pattern[str] | None
  61. allow_inf_nan: bool | None
  62. max_digits: int | None
  63. decimal_places: int | None
  64. union_mode: Literal['smart', 'left_to_right'] | None
  65. discriminator: str | types.Discriminator | None
  66. deprecated: Deprecated | str | bool | None
  67. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
  68. frozen: bool | None
  69. validate_default: bool | None
  70. repr: bool
  71. init: bool | None
  72. init_var: bool | None
  73. kw_only: bool | None
  74. coerce_numbers_to_str: bool | None
  75. fail_fast: bool | None
  76. class _FieldInfoInputs(_FromFieldInfoInputs, total=False):
  77. """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`."""
  78. default: Any
  79. class _FieldInfoAsDict(TypedDict, closed=True):
  80. # TODO PEP 747: use TypeForm:
  81. annotation: Any
  82. metadata: list[Any]
  83. attributes: dict[str, Any]
  84. @final
  85. class FieldInfo(_repr.Representation):
  86. """This class holds information about a field.
  87. `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field]
  88. function is explicitly used.
  89. !!! warning
  90. The `FieldInfo` class is meant to expose information about a field in a Pydantic model or dataclass.
  91. `FieldInfo` instances shouldn't be instantiated directly, nor mutated.
  92. If you need to derive a new model from another one and are willing to alter `FieldInfo` instances,
  93. refer to this [dynamic model example](../examples/dynamic_models.md).
  94. Attributes:
  95. annotation: The type annotation of the field.
  96. default: The default value of the field.
  97. default_factory: A callable to generate the default value. The callable can either take 0 arguments
  98. (in which case it is called as is) or a single argument containing the already validated data.
  99. alias: The alias name of the field.
  100. alias_priority: The priority of the field's alias.
  101. validation_alias: The validation alias of the field.
  102. serialization_alias: The serialization alias of the field.
  103. title: The title of the field.
  104. field_title_generator: A callable that takes a field name and returns title for it.
  105. description: The description of the field.
  106. examples: List of examples of the field.
  107. exclude: Whether to exclude the field from the model serialization.
  108. exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
  109. discriminator: Field name or Discriminator for discriminating the type in a tagged union.
  110. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
  111. or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
  112. json_schema_extra: A dict or callable to provide extra JSON schema properties.
  113. frozen: Whether the field is frozen.
  114. validate_default: Whether to validate the default value of the field.
  115. repr: Whether to include the field in representation of the model.
  116. init: Whether the field should be included in the constructor of the dataclass.
  117. init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
  118. kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
  119. metadata: The metadata list. Contains all the data that isn't expressed as direct `FieldInfo` attributes, including:
  120. * Type-specific constraints, such as `gt` or `min_length` (these are converted to metadata classes such as `annotated_types.Gt`).
  121. * Any other arbitrary object used within [`Annotated`][typing.Annotated] metadata
  122. (e.g. [custom types handlers](../concepts/types.md#as-an-annotation) or any object not recognized by Pydantic).
  123. """
  124. # TODO PEP 747: use TypeForm:
  125. annotation: type[Any] | None
  126. default: Any
  127. default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
  128. alias: str | None
  129. alias_priority: int | None
  130. validation_alias: str | AliasPath | AliasChoices | None
  131. serialization_alias: str | None
  132. title: str | None
  133. field_title_generator: Callable[[str, FieldInfo], str] | None
  134. description: str | None
  135. examples: list[Any] | None
  136. exclude: bool | None
  137. exclude_if: Callable[[Any], bool] | None
  138. discriminator: str | types.Discriminator | None
  139. deprecated: Deprecated | str | bool | None
  140. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
  141. frozen: bool | None
  142. validate_default: bool | None
  143. repr: bool
  144. init: bool | None
  145. init_var: bool | None
  146. kw_only: bool | None
  147. metadata: list[Any]
  148. __slots__ = (
  149. 'annotation',
  150. 'default',
  151. 'default_factory',
  152. 'alias',
  153. 'alias_priority',
  154. 'validation_alias',
  155. 'serialization_alias',
  156. 'title',
  157. 'field_title_generator',
  158. 'description',
  159. 'examples',
  160. 'exclude',
  161. 'exclude_if',
  162. 'discriminator',
  163. 'deprecated',
  164. 'json_schema_extra',
  165. 'frozen',
  166. 'validate_default',
  167. 'repr',
  168. 'init',
  169. 'init_var',
  170. 'kw_only',
  171. 'metadata',
  172. '_attributes_set',
  173. '_qualifiers',
  174. '_complete',
  175. '_original_assignment',
  176. '_original_annotation',
  177. '_final',
  178. )
  179. # used to convert kwargs to metadata/constraints,
  180. # None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
  181. metadata_lookup: ClassVar[dict[str, Callable[[Any], Any] | None]] = {
  182. 'strict': types.Strict,
  183. 'gt': annotated_types.Gt,
  184. 'ge': annotated_types.Ge,
  185. 'lt': annotated_types.Lt,
  186. 'le': annotated_types.Le,
  187. 'multiple_of': annotated_types.MultipleOf,
  188. 'min_length': annotated_types.MinLen,
  189. 'max_length': annotated_types.MaxLen,
  190. 'pattern': None,
  191. 'allow_inf_nan': None,
  192. 'max_digits': None,
  193. 'decimal_places': None,
  194. 'union_mode': None,
  195. 'coerce_numbers_to_str': None,
  196. 'fail_fast': types.FailFast,
  197. }
  198. def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None:
  199. """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
  200. or one of the constructor classmethods.
  201. See the signature of `pydantic.fields.Field` for more details about the expected arguments.
  202. """
  203. # Tracking the explicitly set attributes is necessary to correctly merge `Field()` functions
  204. # (e.g. with `Annotated[int, Field(alias='a'), Field(alias=None)]`, even though `None` is the default value,
  205. # we need to track that `alias=None` was explicitly set):
  206. self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset and k not in self.metadata_lookup}
  207. kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore
  208. self.annotation = kwargs.get('annotation')
  209. # Note: in theory, the second `pop()` arguments are not required below, as defaults are already set from `_DefaultsValues`.
  210. default = kwargs.pop('default', PydanticUndefined)
  211. if default is Ellipsis:
  212. self.default = PydanticUndefined
  213. self._attributes_set.pop('default', None)
  214. else:
  215. self.default = default
  216. self.default_factory = kwargs.pop('default_factory', None)
  217. if self.default is not PydanticUndefined and self.default_factory is not None:
  218. raise TypeError('cannot specify both default and default_factory')
  219. self.alias = kwargs.pop('alias', None)
  220. self.validation_alias = kwargs.pop('validation_alias', None)
  221. self.serialization_alias = kwargs.pop('serialization_alias', None)
  222. alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias))
  223. self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None
  224. self.title = kwargs.pop('title', None)
  225. self.field_title_generator = kwargs.pop('field_title_generator', None)
  226. self.description = kwargs.pop('description', None)
  227. self.examples = kwargs.pop('examples', None)
  228. self.exclude = kwargs.pop('exclude', None)
  229. self.exclude_if = kwargs.pop('exclude_if', None)
  230. self.discriminator = kwargs.pop('discriminator', None)
  231. # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
  232. self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None))
  233. self.repr = kwargs.pop('repr', True)
  234. self.json_schema_extra = kwargs.pop('json_schema_extra', None)
  235. self.validate_default = kwargs.pop('validate_default', None)
  236. self.frozen = kwargs.pop('frozen', None)
  237. # currently only used on dataclasses
  238. self.init = kwargs.pop('init', None)
  239. self.init_var = kwargs.pop('init_var', None)
  240. self.kw_only = kwargs.pop('kw_only', None)
  241. self.metadata = self._collect_metadata(kwargs) # type: ignore
  242. # Private attributes:
  243. self._qualifiers: set[Qualifier] = set()
  244. # Used to rebuild FieldInfo instances:
  245. self._complete = True
  246. self._original_annotation: Any = PydanticUndefined
  247. self._original_assignment: Any = PydanticUndefined
  248. # Used to track whether the `FieldInfo` instance represents the data about a field (and is exposed in `model_fields`/`__pydantic_fields__`),
  249. # or if it is the result of the `Field()` function being used as metadata in an `Annotated` type/as an assignment
  250. # (not an ideal pattern, see https://github.com/pydantic/pydantic/issues/11122):
  251. self._final = False
  252. @staticmethod
  253. def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo:
  254. """Create a new `FieldInfo` object with the `Field` function.
  255. Args:
  256. default: The default value for the field. Defaults to Undefined.
  257. **kwargs: Additional arguments dictionary.
  258. Raises:
  259. TypeError: If 'annotation' is passed as a keyword argument.
  260. Returns:
  261. A new FieldInfo object with the given parameters.
  262. Example:
  263. This is how you can create a field with default value like this:
  264. ```python
  265. import pydantic
  266. class MyModel(pydantic.BaseModel):
  267. foo: int = pydantic.Field(4)
  268. ```
  269. """
  270. if 'annotation' in kwargs:
  271. raise TypeError('"annotation" is not permitted as a Field keyword argument')
  272. return FieldInfo(default=default, **kwargs)
  273. @staticmethod
  274. def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo:
  275. """Creates a `FieldInfo` instance from a bare annotation.
  276. This function is used internally to create a `FieldInfo` from a bare annotation like this:
  277. ```python
  278. import pydantic
  279. class MyModel(pydantic.BaseModel):
  280. foo: int # <-- like this
  281. ```
  282. We also account for the case where the annotation can be an instance of `Annotated` and where
  283. one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
  284. ```python
  285. from typing import Annotated
  286. import annotated_types
  287. import pydantic
  288. class MyModel(pydantic.BaseModel):
  289. foo: Annotated[int, annotated_types.Gt(42)]
  290. bar: Annotated[int, pydantic.Field(gt=42)]
  291. ```
  292. Args:
  293. annotation: An annotation object.
  294. Returns:
  295. An instance of the field metadata.
  296. """
  297. try:
  298. inspected_ann = inspect_annotation(
  299. annotation,
  300. annotation_source=_source,
  301. unpack_type_aliases='skip',
  302. )
  303. except ForbiddenQualifier as e:
  304. raise PydanticForbiddenQualifier(e.qualifier, annotation)
  305. # TODO check for classvar and error?
  306. # No assigned value, this happens when using a bare `Final` qualifier (also for other
  307. # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
  308. # because we don't have any assigned value.
  309. type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
  310. final = 'final' in inspected_ann.qualifiers
  311. metadata = inspected_ann.metadata
  312. attr_overrides = {'annotation': type_expr}
  313. if final:
  314. attr_overrides['frozen'] = True
  315. field_info = FieldInfo._construct(metadata, **attr_overrides)
  316. field_info._qualifiers = inspected_ann.qualifiers
  317. field_info._final = True
  318. return field_info
  319. @staticmethod
  320. def from_annotated_attribute(
  321. annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
  322. ) -> FieldInfo:
  323. """Create `FieldInfo` from an annotation with a default value.
  324. This is used in cases like the following:
  325. ```python
  326. from typing import Annotated
  327. import annotated_types
  328. import pydantic
  329. class MyModel(pydantic.BaseModel):
  330. foo: int = 4 # <-- like this
  331. bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
  332. spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
  333. ```
  334. Args:
  335. annotation: The type annotation of the field.
  336. default: The default value of the field.
  337. Returns:
  338. A field object with the passed values.
  339. """
  340. if annotation is not MISSING and annotation is default:
  341. raise PydanticUserError(
  342. 'Error when building FieldInfo from annotated attribute. '
  343. "Make sure you don't have any field name clashing with a type annotation.",
  344. code='unevaluable-type-annotation',
  345. )
  346. try:
  347. inspected_ann = inspect_annotation(
  348. annotation,
  349. annotation_source=_source,
  350. unpack_type_aliases='skip',
  351. )
  352. except ForbiddenQualifier as e:
  353. raise PydanticForbiddenQualifier(e.qualifier, annotation)
  354. # TODO check for classvar and error?
  355. # TODO infer from the default, this can be done in v3 once we treat final fields with
  356. # a default as proper fields and not class variables:
  357. type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
  358. final = 'final' in inspected_ann.qualifiers
  359. metadata = inspected_ann.metadata
  360. # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend
  361. # metadata from the assignment at the beginning of the metadata. Changing this is only
  362. # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507
  363. prepend_metadata: list[Any] | None = None
  364. attr_overrides = {'annotation': type_expr}
  365. if final:
  366. attr_overrides['frozen'] = True
  367. # HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
  368. # instance's type to be preserved when constructing new models with its subclasses as assignments.
  369. # This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
  370. if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo:
  371. field_info = default._copy()
  372. field_info._attributes_set.update(attr_overrides)
  373. for k, v in attr_overrides.items():
  374. setattr(field_info, k, v)
  375. return field_info
  376. if isinstance(default, FieldInfo):
  377. default_copy = default._copy() # Copy unnecessary when we remove HACK 1.
  378. prepend_metadata = default_copy.metadata
  379. default_copy.metadata = []
  380. metadata = metadata + [default_copy]
  381. elif isinstance(default, dataclasses.Field):
  382. from_field = FieldInfo._from_dataclass_field(default)
  383. prepend_metadata = from_field.metadata # Unnecessary when we remove HACK 1.
  384. from_field.metadata = []
  385. metadata = metadata + [from_field]
  386. if 'init_var' in inspected_ann.qualifiers:
  387. attr_overrides['init_var'] = True
  388. if (init := getattr(default, 'init', None)) is not None:
  389. attr_overrides['init'] = init
  390. if (kw_only := getattr(default, 'kw_only', None)) is not None:
  391. attr_overrides['kw_only'] = kw_only
  392. else:
  393. # `default` is the actual default value
  394. attr_overrides['default'] = default
  395. field_info = FieldInfo._construct(
  396. prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
  397. )
  398. field_info._qualifiers = inspected_ann.qualifiers
  399. field_info._final = True
  400. return field_info
  401. @classmethod
  402. def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self:
  403. """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata.
  404. With the following example:
  405. ```python {test="skip" lint="skip"}
  406. class Model(BaseModel):
  407. f: Annotated[int, Gt(1), Field(description='desc', lt=2)]
  408. ```
  409. `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right:
  410. - If the element is a `Field()` function (which is itself a `FieldInfo` instance), the field attributes (such as
  411. `description`) are saved to be set on the final `FieldInfo` instance.
  412. On the other hand, some kwargs (such as `lt`) are stored as `metadata` (see `FieldInfo.__init__()`, calling
  413. `FieldInfo._collect_metadata()`). In this case, the final metadata list is extended with the one from this instance.
  414. - Else, the element is considered as a single metadata object, and is appended to the final metadata list.
  415. Args:
  416. metadata: The list of metadata elements to merge together. If the `FieldInfo` instance to be constructed is for
  417. a field with an assigned `Field()`, this `Field()` assignment should be added as the last element of the
  418. provided metadata.
  419. **attr_overrides: Extra attributes that should be set on the final merged `FieldInfo` instance.
  420. Returns:
  421. The final merged `FieldInfo` instance.
  422. """
  423. merged_metadata: list[Any] = []
  424. merged_kwargs: dict[str, Any] = {}
  425. for meta in metadata:
  426. if isinstance(meta, FieldInfo):
  427. merged_metadata.extend(meta.metadata)
  428. new_js_extra: JsonDict | None = None
  429. current_js_extra = meta.json_schema_extra
  430. if current_js_extra is not None and 'json_schema_extra' in merged_kwargs:
  431. # We need to merge `json_schema_extra`'s:
  432. existing_js_extra = merged_kwargs['json_schema_extra']
  433. if isinstance(existing_js_extra, dict):
  434. if isinstance(current_js_extra, dict):
  435. new_js_extra = {
  436. **existing_js_extra,
  437. **current_js_extra,
  438. }
  439. elif callable(current_js_extra):
  440. warn(
  441. 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
  442. 'The `callable` type is being ignored. '
  443. "If you'd like support for this behavior, please open an issue on pydantic.",
  444. UserWarning,
  445. )
  446. elif callable(existing_js_extra) and isinstance(current_js_extra, dict):
  447. warn(
  448. 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
  449. 'The `callable` type is being ignored. '
  450. "If you'd like support for this behavior, please open an issue on pydantic.",
  451. UserWarning,
  452. )
  453. # HACK: It is common for users to define "make model partial" (or similar) utilities, that
  454. # convert all model fields to be optional (i.e. have a default value). To do so, they mutate
  455. # each `FieldInfo` instance from `model_fields` to set a `default`, and use `create_model()`
  456. # with `Annotated[<orig_type> | None, mutated_field_info]`` as an annotation. However, such
  457. # mutations (by doing simple assignments) are only accidentally working, because we also
  458. # need to track attributes explicitly set in `_attributes_set` (relying on default values for
  459. # each attribute is *not* enough, for instance with `Annotated[int, Field(alias='a'), Field(alias=None)]`
  460. # the resulting `FieldInfo` should have `alias=None`).
  461. # To mitigate this, we add a special case when a "final" `FieldInfo` instance (that is an instance coming
  462. # from `model_fields`) is used in annotated metadata (or assignment). In this case, we assume *all* attributes
  463. # were explicitly set, and as such we use all of them (and this will correctly pick up the mutations).
  464. # In theory, this shouldn't really be supported, you are only supposed to use the `Field()` function, not
  465. # a `FieldInfo` instance directly (granted, `Field()` returns a `FieldInfo`, see
  466. # https://github.com/pydantic/pydantic/issues/11122):
  467. if meta._final:
  468. merged_kwargs.update({attr: getattr(meta, attr) for attr in _Attrs})
  469. else:
  470. merged_kwargs.update(meta._attributes_set)
  471. if new_js_extra is not None:
  472. merged_kwargs['json_schema_extra'] = new_js_extra
  473. elif typing_objects.is_deprecated(meta):
  474. merged_kwargs['deprecated'] = meta
  475. else:
  476. merged_metadata.append(meta)
  477. merged_kwargs.update(attr_overrides)
  478. merged_field_info = cls(**merged_kwargs)
  479. merged_field_info.metadata = merged_metadata
  480. return merged_field_info
  481. @staticmethod
  482. @typing_extensions.deprecated(
  483. "The 'merge_field_infos()' method is deprecated and will be removed in a future version. "
  484. 'If you relied on this method, please open an issue in the Pydantic issue tracker.',
  485. category=None,
  486. )
  487. def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
  488. """Merge `FieldInfo` instances keeping only explicitly set attributes.
  489. Later `FieldInfo` instances override earlier ones.
  490. Returns:
  491. FieldInfo: A merged FieldInfo instance.
  492. """
  493. if len(field_infos) == 1:
  494. # No merging necessary, but we still need to make a copy and apply the overrides
  495. field_info = field_infos[0]._copy()
  496. field_info._attributes_set.update(overrides)
  497. default_override = overrides.pop('default', PydanticUndefined)
  498. if default_override is Ellipsis:
  499. default_override = PydanticUndefined
  500. if default_override is not PydanticUndefined:
  501. field_info.default = default_override
  502. for k, v in overrides.items():
  503. setattr(field_info, k, v)
  504. return field_info # type: ignore
  505. merged_field_info_kwargs: dict[str, Any] = {}
  506. metadata = {}
  507. for field_info in field_infos:
  508. attributes_set = field_info._attributes_set.copy()
  509. try:
  510. json_schema_extra = attributes_set.pop('json_schema_extra')
  511. existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra')
  512. if existing_json_schema_extra is None:
  513. merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
  514. if isinstance(existing_json_schema_extra, dict):
  515. if isinstance(json_schema_extra, dict):
  516. merged_field_info_kwargs['json_schema_extra'] = {
  517. **existing_json_schema_extra,
  518. **json_schema_extra,
  519. }
  520. if callable(json_schema_extra):
  521. warn(
  522. 'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
  523. 'The `callable` type is being ignored.'
  524. "If you'd like support for this behavior, please open an issue on pydantic.",
  525. PydanticJsonSchemaWarning,
  526. )
  527. elif callable(json_schema_extra):
  528. # if ever there's a case of a callable, we'll just keep the last json schema extra spec
  529. merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
  530. except KeyError:
  531. pass
  532. # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
  533. merged_field_info_kwargs.update(attributes_set)
  534. for x in field_info.metadata:
  535. if not isinstance(x, FieldInfo):
  536. metadata[type(x)] = x
  537. merged_field_info_kwargs.update(overrides)
  538. field_info = FieldInfo(**merged_field_info_kwargs)
  539. field_info.metadata = list(metadata.values())
  540. return field_info
  541. @staticmethod
  542. def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo:
  543. """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
  544. Args:
  545. dc_field: The `dataclasses.Field` instance to convert.
  546. Returns:
  547. The corresponding `FieldInfo` instance.
  548. Raises:
  549. TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
  550. """
  551. default = dc_field.default
  552. if default is dataclasses.MISSING:
  553. default = _Unset
  554. if dc_field.default_factory is dataclasses.MISSING:
  555. default_factory = _Unset
  556. else:
  557. default_factory = dc_field.default_factory
  558. # use the `Field` function so in correct kwargs raise the correct `TypeError`
  559. dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES}
  560. if sys.version_info >= (3, 14) and dc_field.doc is not None:
  561. dc_field_metadata['description'] = dc_field.doc
  562. return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue]
  563. @staticmethod
  564. def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]:
  565. """Collect annotations from kwargs.
  566. Args:
  567. kwargs: Keyword arguments passed to the function.
  568. Returns:
  569. A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
  570. `PydanticMetadata`.
  571. """
  572. metadata: list[Any] = []
  573. general_metadata = {}
  574. for key, value in list(kwargs.items()):
  575. try:
  576. marker = FieldInfo.metadata_lookup[key]
  577. except KeyError:
  578. continue
  579. del kwargs[key]
  580. if value is not None:
  581. if marker is None:
  582. general_metadata[key] = value
  583. else:
  584. metadata.append(marker(value))
  585. if general_metadata:
  586. metadata.append(_fields.pydantic_general_metadata(**general_metadata))
  587. return metadata
  588. @property
  589. def deprecation_message(self) -> str | None:
  590. """The deprecation message to be emitted, or `None` if not set."""
  591. if self.deprecated is None:
  592. return None
  593. if isinstance(self.deprecated, bool):
  594. return 'deprecated' if self.deprecated else None
  595. return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
  596. @property
  597. def default_factory_takes_validated_data(self) -> bool | None:
  598. """Whether the provided default factory callable has a validated data parameter.
  599. Returns `None` if no default factory is set.
  600. """
  601. if self.default_factory is not None:
  602. return _fields.takes_validated_data_argument(self.default_factory)
  603. @overload
  604. def get_default(
  605. self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
  606. ) -> Any: ...
  607. @overload
  608. def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
  609. def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
  610. """Get the default value.
  611. We expose an option for whether to call the default_factory (if present), as calling it may
  612. result in side effects that we want to avoid. However, there are times when it really should
  613. be called (namely, when instantiating a model via `model_construct`).
  614. Args:
  615. call_default_factory: Whether to call the default factory or not.
  616. validated_data: The already validated data to be passed to the default factory.
  617. Returns:
  618. The default value, calling the default factory if requested or `None` if not set.
  619. """
  620. if self.default_factory is None:
  621. return _utils.smart_deepcopy(self.default)
  622. elif call_default_factory:
  623. if self.default_factory_takes_validated_data:
  624. fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory)
  625. if validated_data is None:
  626. raise ValueError(
  627. "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'."
  628. )
  629. return fac(validated_data)
  630. else:
  631. fac = cast('Callable[[], Any]', self.default_factory)
  632. return fac()
  633. else:
  634. return None
  635. def is_required(self) -> bool:
  636. """Check if the field is required (i.e., does not have a default value or factory).
  637. Returns:
  638. `True` if the field is required, `False` otherwise.
  639. """
  640. return self.default is PydanticUndefined and self.default_factory is None
  641. def rebuild_annotation(self) -> Any:
  642. """Attempts to rebuild the original annotation for use in function signatures.
  643. If metadata is present, it adds it to the original annotation using
  644. `Annotated`. Otherwise, it returns the original annotation as-is.
  645. Note that because the metadata has been flattened, the original annotation
  646. may not be reconstructed exactly as originally provided, e.g. if the original
  647. type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
  648. Returns:
  649. The rebuilt annotation.
  650. """
  651. if not self.metadata:
  652. return self.annotation
  653. else:
  654. # Annotated arguments must be a tuple
  655. return Annotated[(self.annotation, *self.metadata)] # type: ignore
  656. def apply_typevars_map(
  657. self,
  658. typevars_map: Mapping[TypeVar, Any] | None,
  659. globalns: GlobalsNamespace | None = None,
  660. localns: MappingNamespace | None = None,
  661. ) -> None:
  662. """Apply a `typevars_map` to the annotation.
  663. This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
  664. This method applies the `typevars_map` to the annotation in place.
  665. Args:
  666. typevars_map: A dictionary mapping type variables to their concrete types.
  667. globalns: The globals namespace to use during type annotation evaluation.
  668. localns: The locals namespace to use during type annotation evaluation.
  669. See Also:
  670. pydantic._internal._generics.replace_types is used for replacing the typevars with
  671. their concrete types.
  672. """
  673. annotation = _generics.replace_types(self.annotation, typevars_map)
  674. annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns)
  675. self.annotation = annotation
  676. if not evaluated:
  677. self._complete = False
  678. self._original_annotation = self.annotation
  679. def asdict(self) -> _FieldInfoAsDict:
  680. """Return a dictionary representation of the `FieldInfo` instance.
  681. The returned value is a dictionary with three items:
  682. * `annotation`: The type annotation of the field.
  683. * `metadata`: The metadata list.
  684. * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
  685. """
  686. return {
  687. 'annotation': self.annotation,
  688. 'metadata': self.metadata,
  689. 'attributes': {attr: getattr(self, attr) for attr in _Attrs},
  690. }
  691. def _copy(self) -> Self:
  692. """Return a copy of the `FieldInfo` instance."""
  693. # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
  694. # by some third-party libraries with extra attributes defined (and as `FieldInfo`
  695. # is slotted, we can't make a copy of the `__dict__`).
  696. copied = copy(self)
  697. for attr_name in ('metadata', '_attributes_set', '_qualifiers'):
  698. # Apply "deep-copy" behavior on collections attributes:
  699. value = getattr(copied, attr_name).copy()
  700. setattr(copied, attr_name, value)
  701. return copied
  702. def __repr_args__(self) -> ReprArgs:
  703. yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation))
  704. yield 'required', self.is_required()
  705. for s in self.__slots__:
  706. # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
  707. # By yielding a three-tuple:
  708. if s in (
  709. 'annotation',
  710. '_attributes_set',
  711. '_qualifiers',
  712. '_complete',
  713. '_original_assignment',
  714. '_original_annotation',
  715. '_final',
  716. ):
  717. continue
  718. elif s == 'metadata' and not self.metadata:
  719. continue
  720. elif s == 'repr' and self.repr is True:
  721. continue
  722. if s == 'frozen' and self.frozen is False:
  723. continue
  724. if s == 'validation_alias' and self.validation_alias == self.alias:
  725. continue
  726. if s == 'serialization_alias' and self.serialization_alias == self.alias:
  727. continue
  728. if s == 'default' and self.default is not PydanticUndefined:
  729. yield 'default', self.default
  730. elif s == 'default_factory' and self.default_factory is not None:
  731. yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory))
  732. else:
  733. value = getattr(self, s)
  734. if value is not None and value is not PydanticUndefined:
  735. yield s, value
  736. class _EmptyKwargs(TypedDict):
  737. """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`."""
  738. _Attrs = {
  739. 'default': ...,
  740. 'default_factory': None,
  741. 'alias': None,
  742. 'alias_priority': None,
  743. 'validation_alias': None,
  744. 'serialization_alias': None,
  745. 'title': None,
  746. 'field_title_generator': None,
  747. 'description': None,
  748. 'examples': None,
  749. 'exclude': None,
  750. 'exclude_if': None,
  751. 'discriminator': None,
  752. 'deprecated': None,
  753. 'json_schema_extra': None,
  754. 'frozen': None,
  755. 'validate_default': None,
  756. 'repr': True,
  757. 'init': None,
  758. 'init_var': None,
  759. 'kw_only': None,
  760. }
  761. _DefaultValues = {
  762. **_Attrs,
  763. 'kw_only': None,
  764. 'pattern': None,
  765. 'strict': None,
  766. 'gt': None,
  767. 'ge': None,
  768. 'lt': None,
  769. 'le': None,
  770. 'multiple_of': None,
  771. 'allow_inf_nan': None,
  772. 'max_digits': None,
  773. 'decimal_places': None,
  774. 'min_length': None,
  775. 'max_length': None,
  776. 'coerce_numbers_to_str': None,
  777. }
  778. _T = TypeVar('_T')
  779. # NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
  780. # to understand the magic that happens at runtime with the following overloads:
  781. @overload # type hint the return value as `Any` to avoid type checking regressions when using `...`.
  782. def Field(
  783. default: ellipsis, # noqa: F821 # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9
  784. *,
  785. alias: str | None = _Unset,
  786. alias_priority: int | None = _Unset,
  787. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  788. serialization_alias: str | None = _Unset,
  789. title: str | None = _Unset,
  790. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  791. description: str | None = _Unset,
  792. examples: list[Any] | None = _Unset,
  793. exclude: bool | None = _Unset,
  794. exclude_if: Callable[[Any], bool] | None = _Unset,
  795. discriminator: str | types.Discriminator | None = _Unset,
  796. deprecated: Deprecated | str | bool | None = _Unset,
  797. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  798. frozen: bool | None = _Unset,
  799. validate_default: bool | None = _Unset,
  800. repr: bool = _Unset,
  801. init: bool | None = _Unset,
  802. init_var: bool | None = _Unset,
  803. kw_only: bool | None = _Unset,
  804. pattern: str | re.Pattern[str] | None = _Unset,
  805. strict: bool | None = _Unset,
  806. coerce_numbers_to_str: bool | None = _Unset,
  807. gt: annotated_types.SupportsGt | None = _Unset,
  808. ge: annotated_types.SupportsGe | None = _Unset,
  809. lt: annotated_types.SupportsLt | None = _Unset,
  810. le: annotated_types.SupportsLe | None = _Unset,
  811. multiple_of: float | None = _Unset,
  812. allow_inf_nan: bool | None = _Unset,
  813. max_digits: int | None = _Unset,
  814. decimal_places: int | None = _Unset,
  815. min_length: int | None = _Unset,
  816. max_length: int | None = _Unset,
  817. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  818. fail_fast: bool | None = _Unset,
  819. **extra: Unpack[_EmptyKwargs],
  820. ) -> Any: ...
  821. @overload # `default` argument set, validate_default=True (no type checking on the default value)
  822. def Field(
  823. default: Any,
  824. *,
  825. alias: str | None = _Unset,
  826. alias_priority: int | None = _Unset,
  827. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  828. serialization_alias: str | None = _Unset,
  829. title: str | None = _Unset,
  830. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  831. description: str | None = _Unset,
  832. examples: list[Any] | None = _Unset,
  833. exclude: bool | None = _Unset,
  834. exclude_if: Callable[[Any], bool] | None = _Unset,
  835. discriminator: str | types.Discriminator | None = _Unset,
  836. deprecated: Deprecated | str | bool | None = _Unset,
  837. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  838. frozen: bool | None = _Unset,
  839. validate_default: Literal[True],
  840. repr: bool = _Unset,
  841. init: bool | None = _Unset,
  842. init_var: bool | None = _Unset,
  843. kw_only: bool | None = _Unset,
  844. pattern: str | re.Pattern[str] | None = _Unset,
  845. strict: bool | None = _Unset,
  846. coerce_numbers_to_str: bool | None = _Unset,
  847. gt: annotated_types.SupportsGt | None = _Unset,
  848. ge: annotated_types.SupportsGe | None = _Unset,
  849. lt: annotated_types.SupportsLt | None = _Unset,
  850. le: annotated_types.SupportsLe | None = _Unset,
  851. multiple_of: float | None = _Unset,
  852. allow_inf_nan: bool | None = _Unset,
  853. max_digits: int | None = _Unset,
  854. decimal_places: int | None = _Unset,
  855. min_length: int | None = _Unset,
  856. max_length: int | None = _Unset,
  857. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  858. fail_fast: bool | None = _Unset,
  859. **extra: Unpack[_EmptyKwargs],
  860. ) -> Any: ...
  861. @overload # `default` argument set, validate_default=False or unset
  862. def Field(
  863. default: _T,
  864. *,
  865. alias: str | None = _Unset,
  866. alias_priority: int | None = _Unset,
  867. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  868. serialization_alias: str | None = _Unset,
  869. title: str | None = _Unset,
  870. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  871. description: str | None = _Unset,
  872. examples: list[Any] | None = _Unset,
  873. exclude: bool | None = _Unset,
  874. # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
  875. # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
  876. # `a: int = Field(default_factory=str)` results in a false negative).
  877. exclude_if: Callable[[Any], bool] | None = _Unset,
  878. discriminator: str | types.Discriminator | None = _Unset,
  879. deprecated: Deprecated | str | bool | None = _Unset,
  880. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  881. frozen: bool | None = _Unset,
  882. validate_default: Literal[False] = ...,
  883. repr: bool = _Unset,
  884. init: bool | None = _Unset,
  885. init_var: bool | None = _Unset,
  886. kw_only: bool | None = _Unset,
  887. pattern: str | re.Pattern[str] | None = _Unset,
  888. strict: bool | None = _Unset,
  889. coerce_numbers_to_str: bool | None = _Unset,
  890. gt: annotated_types.SupportsGt | None = _Unset,
  891. ge: annotated_types.SupportsGe | None = _Unset,
  892. lt: annotated_types.SupportsLt | None = _Unset,
  893. le: annotated_types.SupportsLe | None = _Unset,
  894. multiple_of: float | None = _Unset,
  895. allow_inf_nan: bool | None = _Unset,
  896. max_digits: int | None = _Unset,
  897. decimal_places: int | None = _Unset,
  898. min_length: int | None = _Unset,
  899. max_length: int | None = _Unset,
  900. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  901. fail_fast: bool | None = _Unset,
  902. **extra: Unpack[_EmptyKwargs],
  903. ) -> _T: ...
  904. @overload # `default_factory` argument set, validate_default=True (no type checking on the default value)
  905. def Field( # pyright: ignore[reportOverlappingOverload]
  906. *,
  907. default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
  908. alias: str | None = _Unset,
  909. alias_priority: int | None = _Unset,
  910. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  911. serialization_alias: str | None = _Unset,
  912. title: str | None = _Unset,
  913. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  914. description: str | None = _Unset,
  915. examples: list[Any] | None = _Unset,
  916. exclude: bool | None = _Unset,
  917. exclude_if: Callable[[Any], bool] | None = _Unset,
  918. discriminator: str | types.Discriminator | None = _Unset,
  919. deprecated: Deprecated | str | bool | None = _Unset,
  920. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  921. frozen: bool | None = _Unset,
  922. validate_default: Literal[True],
  923. repr: bool = _Unset,
  924. init: bool | None = _Unset,
  925. init_var: bool | None = _Unset,
  926. kw_only: bool | None = _Unset,
  927. pattern: str | re.Pattern[str] | None = _Unset,
  928. strict: bool | None = _Unset,
  929. coerce_numbers_to_str: bool | None = _Unset,
  930. gt: annotated_types.SupportsGt | None = _Unset,
  931. ge: annotated_types.SupportsGe | None = _Unset,
  932. lt: annotated_types.SupportsLt | None = _Unset,
  933. le: annotated_types.SupportsLe | None = _Unset,
  934. multiple_of: float | None = _Unset,
  935. allow_inf_nan: bool | None = _Unset,
  936. max_digits: int | None = _Unset,
  937. decimal_places: int | None = _Unset,
  938. min_length: int | None = _Unset,
  939. max_length: int | None = _Unset,
  940. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  941. fail_fast: bool | None = _Unset,
  942. **extra: Unpack[_EmptyKwargs],
  943. ) -> Any: ...
  944. @overload # `default_factory` argument set, validate_default=False or unset
  945. def Field(
  946. *,
  947. default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
  948. alias: str | None = _Unset,
  949. alias_priority: int | None = _Unset,
  950. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  951. serialization_alias: str | None = _Unset,
  952. title: str | None = _Unset,
  953. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  954. description: str | None = _Unset,
  955. examples: list[Any] | None = _Unset,
  956. exclude: bool | None = _Unset,
  957. # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
  958. # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
  959. # `a: int = Field(default_factory=str)` results in a false negative).
  960. exclude_if: Callable[[Any], bool] | None = _Unset,
  961. discriminator: str | types.Discriminator | None = _Unset,
  962. deprecated: Deprecated | str | bool | None = _Unset,
  963. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  964. frozen: bool | None = _Unset,
  965. validate_default: Literal[False] | None = _Unset,
  966. repr: bool = _Unset,
  967. init: bool | None = _Unset,
  968. init_var: bool | None = _Unset,
  969. kw_only: bool | None = _Unset,
  970. pattern: str | re.Pattern[str] | None = _Unset,
  971. strict: bool | None = _Unset,
  972. coerce_numbers_to_str: bool | None = _Unset,
  973. gt: annotated_types.SupportsGt | None = _Unset,
  974. ge: annotated_types.SupportsGe | None = _Unset,
  975. lt: annotated_types.SupportsLt | None = _Unset,
  976. le: annotated_types.SupportsLe | None = _Unset,
  977. multiple_of: float | None = _Unset,
  978. allow_inf_nan: bool | None = _Unset,
  979. max_digits: int | None = _Unset,
  980. decimal_places: int | None = _Unset,
  981. min_length: int | None = _Unset,
  982. max_length: int | None = _Unset,
  983. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  984. fail_fast: bool | None = _Unset,
  985. **extra: Unpack[_EmptyKwargs],
  986. ) -> _T: ...
  987. @overload
  988. def Field( # No default set
  989. *,
  990. alias: str | None = _Unset,
  991. alias_priority: int | None = _Unset,
  992. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  993. serialization_alias: str | None = _Unset,
  994. title: str | None = _Unset,
  995. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  996. description: str | None = _Unset,
  997. examples: list[Any] | None = _Unset,
  998. exclude: bool | None = _Unset,
  999. exclude_if: Callable[[Any], bool] | None = _Unset,
  1000. discriminator: str | types.Discriminator | None = _Unset,
  1001. deprecated: Deprecated | str | bool | None = _Unset,
  1002. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  1003. frozen: bool | None = _Unset,
  1004. validate_default: bool | None = _Unset,
  1005. repr: bool = _Unset,
  1006. init: bool | None = _Unset,
  1007. init_var: bool | None = _Unset,
  1008. kw_only: bool | None = _Unset,
  1009. pattern: str | re.Pattern[str] | None = _Unset,
  1010. strict: bool | None = _Unset,
  1011. coerce_numbers_to_str: bool | None = _Unset,
  1012. gt: annotated_types.SupportsGt | None = _Unset,
  1013. ge: annotated_types.SupportsGe | None = _Unset,
  1014. lt: annotated_types.SupportsLt | None = _Unset,
  1015. le: annotated_types.SupportsLe | None = _Unset,
  1016. multiple_of: float | None = _Unset,
  1017. allow_inf_nan: bool | None = _Unset,
  1018. max_digits: int | None = _Unset,
  1019. decimal_places: int | None = _Unset,
  1020. min_length: int | None = _Unset,
  1021. max_length: int | None = _Unset,
  1022. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  1023. fail_fast: bool | None = _Unset,
  1024. **extra: Unpack[_EmptyKwargs],
  1025. ) -> Any: ...
  1026. def Field( # noqa: C901
  1027. default: Any = PydanticUndefined,
  1028. *,
  1029. default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
  1030. alias: str | None = _Unset,
  1031. alias_priority: int | None = _Unset,
  1032. validation_alias: str | AliasPath | AliasChoices | None = _Unset,
  1033. serialization_alias: str | None = _Unset,
  1034. title: str | None = _Unset,
  1035. field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
  1036. description: str | None = _Unset,
  1037. examples: list[Any] | None = _Unset,
  1038. exclude: bool | None = _Unset,
  1039. exclude_if: Callable[[Any], bool] | None = _Unset,
  1040. discriminator: str | types.Discriminator | None = _Unset,
  1041. deprecated: Deprecated | str | bool | None = _Unset,
  1042. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
  1043. frozen: bool | None = _Unset,
  1044. validate_default: bool | None = _Unset,
  1045. repr: bool = _Unset,
  1046. init: bool | None = _Unset,
  1047. init_var: bool | None = _Unset,
  1048. kw_only: bool | None = _Unset,
  1049. pattern: str | re.Pattern[str] | None = _Unset,
  1050. strict: bool | None = _Unset,
  1051. coerce_numbers_to_str: bool | None = _Unset,
  1052. gt: annotated_types.SupportsGt | None = _Unset,
  1053. ge: annotated_types.SupportsGe | None = _Unset,
  1054. lt: annotated_types.SupportsLt | None = _Unset,
  1055. le: annotated_types.SupportsLe | None = _Unset,
  1056. multiple_of: float | None = _Unset,
  1057. allow_inf_nan: bool | None = _Unset,
  1058. max_digits: int | None = _Unset,
  1059. decimal_places: int | None = _Unset,
  1060. min_length: int | None = _Unset,
  1061. max_length: int | None = _Unset,
  1062. union_mode: Literal['smart', 'left_to_right'] = _Unset,
  1063. fail_fast: bool | None = _Unset,
  1064. **extra: Unpack[_EmptyKwargs],
  1065. ) -> Any:
  1066. """!!! abstract "Usage Documentation"
  1067. [Fields](../concepts/fields.md)
  1068. Create a field for objects that can be configured.
  1069. Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
  1070. apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
  1071. Note:
  1072. - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None`
  1073. Args:
  1074. default: Default value if the field is not set.
  1075. default_factory: A callable to generate the default value. The callable can either take 0 arguments
  1076. (in which case it is called as is) or a single argument containing the already validated data.
  1077. alias: The name to use for the attribute when validating or serializing by alias.
  1078. This is often used for things like converting between snake and camel case.
  1079. alias_priority: Priority of the alias. This affects whether an alias generator is used.
  1080. validation_alias: Like `alias`, but only affects validation, not serialization.
  1081. serialization_alias: Like `alias`, but only affects serialization, not validation.
  1082. title: Human-readable title.
  1083. field_title_generator: A callable that takes a field name and returns title for it.
  1084. description: Human-readable description.
  1085. examples: Example values for this field.
  1086. exclude: Whether to exclude the field from the model serialization.
  1087. exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
  1088. discriminator: Field name or Discriminator for discriminating the type in a tagged union.
  1089. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
  1090. or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
  1091. json_schema_extra: A dict or callable to provide extra JSON schema properties.
  1092. frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
  1093. validate_default: If `True`, apply validation to the default value every time you create an instance.
  1094. Otherwise, for performance reasons, the default value of the field is trusted and not validated.
  1095. repr: A boolean indicating whether to include the field in the `__repr__` output.
  1096. init: Whether the field should be included in the constructor of the dataclass.
  1097. (Only applies to dataclasses.)
  1098. init_var: Whether the field should _only_ be included in the constructor of the dataclass.
  1099. (Only applies to dataclasses.)
  1100. kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
  1101. (Only applies to dataclasses.)
  1102. coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
  1103. strict: If `True`, strict validation is applied to the field.
  1104. See [Strict Mode](../concepts/strict_mode.md) for details.
  1105. gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
  1106. ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
  1107. lt: Less than. If set, value must be less than this. Only applicable to numbers.
  1108. le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
  1109. multiple_of: Value must be a multiple of this. Only applicable to numbers.
  1110. min_length: Minimum length for iterables.
  1111. max_length: Maximum length for iterables.
  1112. pattern: Pattern for strings (a regular expression).
  1113. allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
  1114. max_digits: Maximum number of allow digits for strings.
  1115. decimal_places: Maximum number of decimal places allowed for numbers.
  1116. union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
  1117. See [Union Mode](../concepts/unions.md#union-modes) for details.
  1118. fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
  1119. This option can be applied only to iterable types (list, tuple, set, and frozenset).
  1120. extra: (Deprecated) Extra fields that will be included in the JSON schema.
  1121. !!! warning Deprecated
  1122. The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
  1123. Returns:
  1124. A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
  1125. type-annotated fields without causing a type error.
  1126. """
  1127. # Check deprecated and removed params from V1. This logic should eventually be removed.
  1128. const = extra.pop('const', None) # type: ignore
  1129. if const is not None:
  1130. raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs')
  1131. min_items = extra.pop('min_items', None) # type: ignore
  1132. if min_items is not None:
  1133. warn(
  1134. '`min_items` is deprecated and will be removed, use `min_length` instead',
  1135. PydanticDeprecatedSince20,
  1136. stacklevel=2,
  1137. )
  1138. if min_length in (None, _Unset):
  1139. min_length = min_items # type: ignore
  1140. max_items = extra.pop('max_items', None) # type: ignore
  1141. if max_items is not None:
  1142. warn(
  1143. '`max_items` is deprecated and will be removed, use `max_length` instead',
  1144. PydanticDeprecatedSince20,
  1145. stacklevel=2,
  1146. )
  1147. if max_length in (None, _Unset):
  1148. max_length = max_items # type: ignore
  1149. unique_items = extra.pop('unique_items', None) # type: ignore
  1150. if unique_items is not None:
  1151. raise PydanticUserError(
  1152. (
  1153. '`unique_items` is removed, use `Set` instead'
  1154. '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
  1155. ),
  1156. code='removed-kwargs',
  1157. )
  1158. allow_mutation = extra.pop('allow_mutation', None) # type: ignore
  1159. if allow_mutation is not None:
  1160. warn(
  1161. '`allow_mutation` is deprecated and will be removed. use `frozen` instead',
  1162. PydanticDeprecatedSince20,
  1163. stacklevel=2,
  1164. )
  1165. if allow_mutation is False:
  1166. frozen = True
  1167. regex = extra.pop('regex', None) # type: ignore
  1168. if regex is not None:
  1169. raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs')
  1170. if extra:
  1171. warn(
  1172. 'Using extra keyword arguments on `Field` is deprecated and will be removed.'
  1173. ' Use `json_schema_extra` instead.'
  1174. f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
  1175. PydanticDeprecatedSince20,
  1176. stacklevel=2,
  1177. )
  1178. if not json_schema_extra or json_schema_extra is _Unset:
  1179. json_schema_extra = extra # type: ignore
  1180. if (
  1181. validation_alias
  1182. and validation_alias is not _Unset
  1183. and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
  1184. ):
  1185. raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')
  1186. if serialization_alias in (_Unset, None) and isinstance(alias, str):
  1187. serialization_alias = alias
  1188. if validation_alias in (_Unset, None):
  1189. validation_alias = alias
  1190. include = extra.pop('include', None) # type: ignore
  1191. if include is not None:
  1192. warn(
  1193. '`include` is deprecated and does nothing. It will be removed, use `exclude` instead',
  1194. PydanticDeprecatedSince20,
  1195. stacklevel=2,
  1196. )
  1197. return FieldInfo.from_field(
  1198. default,
  1199. default_factory=default_factory,
  1200. alias=alias,
  1201. alias_priority=alias_priority,
  1202. validation_alias=validation_alias,
  1203. serialization_alias=serialization_alias,
  1204. title=title,
  1205. field_title_generator=field_title_generator,
  1206. description=description,
  1207. examples=examples,
  1208. exclude=exclude,
  1209. exclude_if=exclude_if,
  1210. discriminator=discriminator,
  1211. deprecated=deprecated,
  1212. json_schema_extra=json_schema_extra,
  1213. frozen=frozen,
  1214. pattern=pattern,
  1215. validate_default=validate_default,
  1216. repr=repr,
  1217. init=init,
  1218. init_var=init_var,
  1219. kw_only=kw_only,
  1220. coerce_numbers_to_str=coerce_numbers_to_str,
  1221. strict=strict,
  1222. gt=gt,
  1223. ge=ge,
  1224. lt=lt,
  1225. le=le,
  1226. multiple_of=multiple_of,
  1227. min_length=min_length,
  1228. max_length=max_length,
  1229. allow_inf_nan=allow_inf_nan,
  1230. max_digits=max_digits,
  1231. decimal_places=decimal_places,
  1232. union_mode=union_mode,
  1233. fail_fast=fail_fast,
  1234. )
  1235. _FIELD_ARG_NAMES = set(inspect.signature(Field).parameters)
  1236. _FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter
  1237. class ModelPrivateAttr(_repr.Representation):
  1238. """A descriptor for private attributes in class models.
  1239. !!! warning
  1240. You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
  1241. `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.)
  1242. Attributes:
  1243. default: The default value of the attribute if not provided.
  1244. default_factory: A callable function that generates the default value of the
  1245. attribute if not provided.
  1246. """
  1247. __slots__ = ('default', 'default_factory')
  1248. def __init__(self, default: Any = PydanticUndefined, *, default_factory: Callable[[], Any] | None = None) -> None:
  1249. if default is Ellipsis:
  1250. self.default = PydanticUndefined
  1251. else:
  1252. self.default = default
  1253. self.default_factory = default_factory
  1254. if not TYPE_CHECKING:
  1255. # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
  1256. def __getattr__(self, item: str) -> Any:
  1257. """This function improves compatibility with custom descriptors by ensuring delegation happens
  1258. as expected when the default value of a private attribute is a descriptor.
  1259. """
  1260. if item in {'__get__', '__set__', '__delete__'}:
  1261. if hasattr(self.default, item):
  1262. return getattr(self.default, item)
  1263. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
  1264. def __set_name__(self, cls: type[Any], name: str) -> None:
  1265. """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
  1266. default = self.default
  1267. if default is PydanticUndefined:
  1268. return
  1269. set_name = getattr(default, '__set_name__', None)
  1270. if callable(set_name):
  1271. set_name(cls, name)
  1272. def get_default(self) -> Any:
  1273. """Retrieve the default value of the object.
  1274. If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.
  1275. If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned.
  1276. Returns:
  1277. The default value of the object.
  1278. """
  1279. return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()
  1280. def __eq__(self, other: Any) -> bool:
  1281. return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
  1282. other.default,
  1283. other.default_factory,
  1284. )
  1285. # NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
  1286. # to understand the magic that happens at runtime.
  1287. @overload # `default` argument set
  1288. def PrivateAttr(
  1289. default: _T,
  1290. *,
  1291. init: Literal[False] = False,
  1292. ) -> _T: ...
  1293. @overload # `default_factory` argument set
  1294. def PrivateAttr(
  1295. *,
  1296. default_factory: Callable[[], _T],
  1297. init: Literal[False] = False,
  1298. ) -> _T: ...
  1299. @overload # No default set
  1300. def PrivateAttr(
  1301. *,
  1302. init: Literal[False] = False,
  1303. ) -> Any: ...
  1304. def PrivateAttr(
  1305. default: Any = PydanticUndefined,
  1306. *,
  1307. default_factory: Callable[[], Any] | None = None,
  1308. init: Literal[False] = False,
  1309. ) -> Any:
  1310. """!!! abstract "Usage Documentation"
  1311. [Private Model Attributes](../concepts/models.md#private-model-attributes)
  1312. Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
  1313. Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
  1314. Private attributes are stored in `__private_attributes__` on the model.
  1315. Args:
  1316. default: The attribute's default value. Defaults to Undefined.
  1317. default_factory: Callable that will be
  1318. called when a default value is needed for this attribute.
  1319. If both `default` and `default_factory` are set, an error will be raised.
  1320. init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
  1321. Returns:
  1322. An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
  1323. Raises:
  1324. ValueError: If both `default` and `default_factory` are set.
  1325. """
  1326. if default is not PydanticUndefined and default_factory is not None:
  1327. raise TypeError('cannot specify both default and default_factory')
  1328. return ModelPrivateAttr(
  1329. default,
  1330. default_factory=default_factory,
  1331. )
  1332. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  1333. class ComputedFieldInfo:
  1334. """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
  1335. Attributes:
  1336. decorator_repr: A class variable representing the decorator string, '@computed_field'.
  1337. wrapped_property: The wrapped computed field property.
  1338. return_type: The type of the computed field property's return value.
  1339. alias: The alias of the property to be used during serialization.
  1340. alias_priority: The priority of the alias. This affects whether an alias generator is used.
  1341. title: Title of the computed field to include in the serialization JSON schema.
  1342. field_title_generator: A callable that takes a field name and returns title for it.
  1343. description: Description of the computed field to include in the serialization JSON schema.
  1344. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
  1345. or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
  1346. examples: Example values of the computed field to include in the serialization JSON schema.
  1347. json_schema_extra: A dict or callable to provide extra JSON schema properties.
  1348. repr: A boolean indicating whether to include the field in the __repr__ output.
  1349. """
  1350. decorator_repr: ClassVar[str] = '@computed_field'
  1351. wrapped_property: property
  1352. return_type: Any
  1353. alias: str | None
  1354. alias_priority: int | None
  1355. title: str | None
  1356. field_title_generator: Callable[[str, ComputedFieldInfo], str] | None
  1357. description: str | None
  1358. deprecated: Deprecated | str | bool | None
  1359. examples: list[Any] | None
  1360. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
  1361. repr: bool
  1362. @property
  1363. def deprecation_message(self) -> str | None:
  1364. """The deprecation message to be emitted, or `None` if not set."""
  1365. if self.deprecated is None:
  1366. return None
  1367. if isinstance(self.deprecated, bool):
  1368. return 'deprecated' if self.deprecated else None
  1369. return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
  1370. def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None:
  1371. """Update the instance from the configuration set on the class this computed field belongs to."""
  1372. title_generator = self.field_title_generator or config_wrapper.field_title_generator
  1373. if title_generator is not None and self.title is None:
  1374. self.title = title_generator(name, self)
  1375. if config_wrapper.alias_generator is not None:
  1376. self._apply_alias_generator(config_wrapper.alias_generator, name)
  1377. def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None:
  1378. """Apply an alias generator to aliases if appropriate.
  1379. Args:
  1380. alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
  1381. name: The name of the computed field from which to generate the alias.
  1382. """
  1383. # Apply an alias_generator if
  1384. # 1. An alias is not specified
  1385. # 2. An alias is specified, but the priority is <= 1
  1386. if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None:
  1387. alias, _, serialization_alias = None, None, None
  1388. if isinstance(alias_generator, AliasGenerator):
  1389. alias, _, serialization_alias = alias_generator.generate_aliases(name)
  1390. elif callable(alias_generator):
  1391. alias = alias_generator(name)
  1392. # if priority is not set, we set to 1
  1393. # which supports the case where the alias_generator from a child class is used
  1394. # to generate an alias for a field in a parent class
  1395. if self.alias_priority is None or self.alias_priority <= 1:
  1396. self.alias_priority = 1
  1397. # if the priority is 1, then we set the aliases to the generated alias
  1398. # note that we use the serialization_alias with priority over alias, as computed_field
  1399. # aliases are used for serialization only (not validation)
  1400. if self.alias_priority == 1:
  1401. self.alias = _utils.get_first_not_none(serialization_alias, alias)
  1402. def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore
  1403. """Returns true if provided property is private, False otherwise."""
  1404. wrapped_name: str = ''
  1405. if isinstance(property_, property):
  1406. wrapped_name = getattr(property_.fget, '__name__', '')
  1407. elif isinstance(property_, cached_property): # type: ignore
  1408. wrapped_name = getattr(property_.func, '__name__', '') # type: ignore
  1409. return wrapped_name.startswith('_') and not wrapped_name.startswith('__')
  1410. # this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
  1411. # See https://github.com/python/typing/issues/985 and linked issues
  1412. PropertyT = TypeVar('PropertyT')
  1413. @overload
  1414. def computed_field(func: PropertyT, /) -> PropertyT: ...
  1415. @overload
  1416. def computed_field(
  1417. *,
  1418. alias: str | None = None,
  1419. alias_priority: int | None = None,
  1420. title: str | None = None,
  1421. field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
  1422. description: str | None = None,
  1423. deprecated: Deprecated | str | bool | None = None,
  1424. examples: list[Any] | None = None,
  1425. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
  1426. repr: bool = True,
  1427. return_type: Any = PydanticUndefined,
  1428. ) -> Callable[[PropertyT], PropertyT]: ...
  1429. def computed_field(
  1430. func: PropertyT | None = None,
  1431. /,
  1432. *,
  1433. alias: str | None = None,
  1434. alias_priority: int | None = None,
  1435. title: str | None = None,
  1436. field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
  1437. description: str | None = None,
  1438. deprecated: Deprecated | str | bool | None = None,
  1439. examples: list[Any] | None = None,
  1440. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
  1441. repr: bool | None = None,
  1442. return_type: Any = PydanticUndefined,
  1443. ) -> PropertyT | Callable[[PropertyT], PropertyT]:
  1444. """!!! abstract "Usage Documentation"
  1445. [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
  1446. Decorator to include `property` and `cached_property` when serializing models or dataclasses.
  1447. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
  1448. ```python
  1449. from pydantic import BaseModel, computed_field
  1450. class Rectangle(BaseModel):
  1451. width: int
  1452. length: int
  1453. @computed_field
  1454. @property
  1455. def area(self) -> int:
  1456. return self.width * self.length
  1457. print(Rectangle(width=3, length=2).model_dump())
  1458. #> {'width': 3, 'length': 2, 'area': 6}
  1459. ```
  1460. If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
  1461. automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
  1462. and confuse static type checkers, thus explicit use of `@property` is recommended.
  1463. !!! warning "Mypy Warning"
  1464. Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
  1465. mypy may throw a `Decorated property not supported` error.
  1466. See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
  1467. To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
  1468. [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
  1469. ```python
  1470. import random
  1471. from pydantic import BaseModel, computed_field
  1472. class Square(BaseModel):
  1473. width: float
  1474. @computed_field
  1475. def area(self) -> float: # converted to a `property` by `computed_field`
  1476. return round(self.width**2, 2)
  1477. @area.setter
  1478. def area(self, new_area: float) -> None:
  1479. self.width = new_area**0.5
  1480. @computed_field(alias='the magic number', repr=False)
  1481. def random_number(self) -> int:
  1482. return random.randint(0, 1_000)
  1483. square = Square(width=1.3)
  1484. # `random_number` does not appear in representation
  1485. print(repr(square))
  1486. #> Square(width=1.3, area=1.69)
  1487. print(square.random_number)
  1488. #> 3
  1489. square.area = 4
  1490. print(square.model_dump_json(by_alias=True))
  1491. #> {"width":2.0,"area":4.0,"the magic number":3}
  1492. ```
  1493. !!! warning "Overriding with `computed_field`"
  1494. You can't override a field from a parent class with a `computed_field` in the child class.
  1495. `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
  1496. See the example below:
  1497. ```python
  1498. from pydantic import BaseModel, computed_field
  1499. class Parent(BaseModel):
  1500. a: str
  1501. try:
  1502. class Child(Parent):
  1503. @computed_field
  1504. @property
  1505. def a(self) -> str:
  1506. return 'new a'
  1507. except TypeError as e:
  1508. print(e)
  1509. '''
  1510. Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
  1511. '''
  1512. ```
  1513. Private properties decorated with `@computed_field` have `repr=False` by default.
  1514. ```python
  1515. from functools import cached_property
  1516. from pydantic import BaseModel, computed_field
  1517. class Model(BaseModel):
  1518. foo: int
  1519. @computed_field
  1520. @cached_property
  1521. def _private_cached_property(self) -> int:
  1522. return -self.foo
  1523. @computed_field
  1524. @property
  1525. def _private_property(self) -> int:
  1526. return -self.foo
  1527. m = Model(foo=1)
  1528. print(repr(m))
  1529. #> Model(foo=1)
  1530. ```
  1531. Args:
  1532. func: the function to wrap.
  1533. alias: alias to use when serializing this computed field, only used when `by_alias=True`
  1534. alias_priority: priority of the alias. This affects whether an alias generator is used
  1535. title: Title to use when including this computed field in JSON Schema
  1536. field_title_generator: A callable that takes a field name and returns title for it.
  1537. description: Description to use when including this computed field in JSON Schema, defaults to the function's
  1538. docstring
  1539. deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
  1540. to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
  1541. `deprecated` decorator.
  1542. examples: Example values to use when including this computed field in JSON Schema
  1543. json_schema_extra: A dict or callable to provide extra JSON schema properties.
  1544. repr: whether to include this computed field in model repr.
  1545. Default is `False` for private properties and `True` for public properties.
  1546. return_type: optional return for serialization logic to expect when serializing to JSON, if included
  1547. this must be correct, otherwise a `TypeError` is raised.
  1548. If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
  1549. objects.
  1550. Returns:
  1551. A proxy wrapper for the property.
  1552. """
  1553. def dec(f: Any) -> Any:
  1554. nonlocal description, deprecated, return_type, alias_priority
  1555. unwrapped = _decorators.unwrap_wrapped_function(f)
  1556. if description is None and unwrapped.__doc__:
  1557. description = inspect.cleandoc(unwrapped.__doc__)
  1558. if deprecated is None and hasattr(unwrapped, '__deprecated__'):
  1559. deprecated = unwrapped.__deprecated__
  1560. # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
  1561. f = _decorators.ensure_property(f)
  1562. alias_priority = (alias_priority or 2) if alias is not None else None
  1563. if repr is None:
  1564. repr_: bool = not _wrapped_property_is_private(property_=f)
  1565. else:
  1566. repr_ = repr
  1567. dec_info = ComputedFieldInfo(
  1568. f,
  1569. return_type,
  1570. alias,
  1571. alias_priority,
  1572. title,
  1573. field_title_generator,
  1574. description,
  1575. deprecated,
  1576. examples,
  1577. json_schema_extra,
  1578. repr_,
  1579. )
  1580. return _decorators.PydanticDescriptorProxy(f, dec_info)
  1581. if func is None:
  1582. return dec
  1583. else:
  1584. return dec(func)