fields.py 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  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, 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. if 'init_var' in inspected_ann.qualifiers:
  382. # Only relevant for dataclasses, when `f: InitVar[<type>] = Field(...)`
  383. # is used:
  384. attr_overrides['init_var'] = True
  385. elif isinstance(default, dataclasses.Field):
  386. from_field = FieldInfo._from_dataclass_field(default)
  387. prepend_metadata = from_field.metadata # Unnecessary when we remove HACK 1.
  388. from_field.metadata = []
  389. metadata = metadata + [from_field]
  390. if 'init_var' in inspected_ann.qualifiers:
  391. attr_overrides['init_var'] = True
  392. if (init := getattr(default, 'init', None)) is not None:
  393. attr_overrides['init'] = init
  394. if (kw_only := getattr(default, 'kw_only', None)) is not None:
  395. attr_overrides['kw_only'] = kw_only
  396. else:
  397. # `default` is the actual default value
  398. attr_overrides['default'] = default
  399. field_info = FieldInfo._construct(
  400. prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
  401. )
  402. field_info._qualifiers = inspected_ann.qualifiers
  403. field_info._final = True
  404. return field_info
  405. @classmethod
  406. def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self:
  407. """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata.
  408. With the following example:
  409. ```python {test="skip" lint="skip"}
  410. class Model(BaseModel):
  411. f: Annotated[int, Gt(1), Field(description='desc', lt=2)]
  412. ```
  413. `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right:
  414. - If the element is a `Field()` function (which is itself a `FieldInfo` instance), the field attributes (such as
  415. `description`) are saved to be set on the final `FieldInfo` instance.
  416. On the other hand, some kwargs (such as `lt`) are stored as `metadata` (see `FieldInfo.__init__()`, calling
  417. `FieldInfo._collect_metadata()`). In this case, the final metadata list is extended with the one from this instance.
  418. - Else, the element is considered as a single metadata object, and is appended to the final metadata list.
  419. Args:
  420. metadata: The list of metadata elements to merge together. If the `FieldInfo` instance to be constructed is for
  421. a field with an assigned `Field()`, this `Field()` assignment should be added as the last element of the
  422. provided metadata.
  423. **attr_overrides: Extra attributes that should be set on the final merged `FieldInfo` instance.
  424. Returns:
  425. The final merged `FieldInfo` instance.
  426. """
  427. merged_metadata: list[Any] = []
  428. merged_kwargs: dict[str, Any] = {}
  429. for meta in metadata:
  430. if isinstance(meta, FieldInfo):
  431. merged_metadata.extend(meta.metadata)
  432. new_js_extra: JsonDict | None = None
  433. current_js_extra = meta.json_schema_extra
  434. if current_js_extra is not None and 'json_schema_extra' in merged_kwargs:
  435. # We need to merge `json_schema_extra`'s:
  436. existing_js_extra = merged_kwargs['json_schema_extra']
  437. if isinstance(existing_js_extra, dict):
  438. if isinstance(current_js_extra, dict):
  439. new_js_extra = {
  440. **existing_js_extra,
  441. **current_js_extra,
  442. }
  443. elif callable(current_js_extra):
  444. warn(
  445. 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
  446. 'The `callable` type is being ignored. '
  447. "If you'd like support for this behavior, please open an issue on pydantic.",
  448. UserWarning,
  449. )
  450. elif callable(existing_js_extra) and isinstance(current_js_extra, dict):
  451. warn(
  452. 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
  453. 'The `callable` type is being ignored. '
  454. "If you'd like support for this behavior, please open an issue on pydantic.",
  455. UserWarning,
  456. )
  457. # HACK: It is common for users to define "make model partial" (or similar) utilities, that
  458. # convert all model fields to be optional (i.e. have a default value). To do so, they mutate
  459. # each `FieldInfo` instance from `model_fields` to set a `default`, and use `create_model()`
  460. # with `Annotated[<orig_type> | None, mutated_field_info]`` as an annotation. However, such
  461. # mutations (by doing simple assignments) are only accidentally working, because we also
  462. # need to track attributes explicitly set in `_attributes_set` (relying on default values for
  463. # each attribute is *not* enough, for instance with `Annotated[int, Field(alias='a'), Field(alias=None)]`
  464. # the resulting `FieldInfo` should have `alias=None`).
  465. # To mitigate this, we add a special case when a "final" `FieldInfo` instance (that is an instance coming
  466. # from `model_fields`) is used in annotated metadata (or assignment). In this case, we assume *all* attributes
  467. # were explicitly set, and as such we use all of them (and this will correctly pick up the mutations).
  468. # In theory, this shouldn't really be supported, you are only supposed to use the `Field()` function, not
  469. # a `FieldInfo` instance directly (granted, `Field()` returns a `FieldInfo`, see
  470. # https://github.com/pydantic/pydantic/issues/11122):
  471. if meta._final:
  472. merged_kwargs.update({attr: getattr(meta, attr) for attr in _Attrs})
  473. else:
  474. merged_kwargs.update(meta._attributes_set)
  475. if new_js_extra is not None:
  476. merged_kwargs['json_schema_extra'] = new_js_extra
  477. elif typing_objects.is_deprecated(meta):
  478. merged_kwargs['deprecated'] = meta
  479. else:
  480. merged_metadata.append(meta)
  481. merged_kwargs.update(attr_overrides)
  482. merged_field_info = cls(**merged_kwargs)
  483. merged_field_info.metadata = merged_metadata
  484. return merged_field_info
  485. @staticmethod
  486. @typing_extensions.deprecated(
  487. "The 'merge_field_infos()' method is deprecated and will be removed in a future version. "
  488. 'If you relied on this method, please open an issue in the Pydantic issue tracker.',
  489. category=None,
  490. )
  491. def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
  492. """Merge `FieldInfo` instances keeping only explicitly set attributes.
  493. Later `FieldInfo` instances override earlier ones.
  494. Returns:
  495. FieldInfo: A merged FieldInfo instance.
  496. """
  497. if len(field_infos) == 1:
  498. # No merging necessary, but we still need to make a copy and apply the overrides
  499. field_info = field_infos[0]._copy()
  500. field_info._attributes_set.update(overrides)
  501. default_override = overrides.pop('default', PydanticUndefined)
  502. if default_override is Ellipsis:
  503. default_override = PydanticUndefined
  504. if default_override is not PydanticUndefined:
  505. field_info.default = default_override
  506. for k, v in overrides.items():
  507. setattr(field_info, k, v)
  508. return field_info # type: ignore
  509. merged_field_info_kwargs: dict[str, Any] = {}
  510. metadata = {}
  511. for field_info in field_infos:
  512. attributes_set = field_info._attributes_set.copy()
  513. try:
  514. json_schema_extra = attributes_set.pop('json_schema_extra')
  515. existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra')
  516. if existing_json_schema_extra is None:
  517. merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
  518. if isinstance(existing_json_schema_extra, dict):
  519. if isinstance(json_schema_extra, dict):
  520. merged_field_info_kwargs['json_schema_extra'] = {
  521. **existing_json_schema_extra,
  522. **json_schema_extra,
  523. }
  524. if callable(json_schema_extra):
  525. warn(
  526. 'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
  527. 'The `callable` type is being ignored.'
  528. "If you'd like support for this behavior, please open an issue on pydantic.",
  529. PydanticJsonSchemaWarning,
  530. )
  531. elif callable(json_schema_extra):
  532. # if ever there's a case of a callable, we'll just keep the last json schema extra spec
  533. merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
  534. except KeyError:
  535. pass
  536. # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
  537. merged_field_info_kwargs.update(attributes_set)
  538. for x in field_info.metadata:
  539. if not isinstance(x, FieldInfo):
  540. metadata[type(x)] = x
  541. merged_field_info_kwargs.update(overrides)
  542. field_info = FieldInfo(**merged_field_info_kwargs)
  543. field_info.metadata = list(metadata.values())
  544. return field_info
  545. @staticmethod
  546. def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo:
  547. """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
  548. Args:
  549. dc_field: The `dataclasses.Field` instance to convert.
  550. Returns:
  551. The corresponding `FieldInfo` instance.
  552. Raises:
  553. TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
  554. """
  555. default = dc_field.default
  556. if default is dataclasses.MISSING:
  557. default = _Unset
  558. if dc_field.default_factory is dataclasses.MISSING:
  559. default_factory = _Unset
  560. else:
  561. default_factory = dc_field.default_factory
  562. # use the `Field` function so in correct kwargs raise the correct `TypeError`
  563. dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES}
  564. if sys.version_info >= (3, 14) and dc_field.doc is not None:
  565. dc_field_metadata['description'] = dc_field.doc
  566. return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue]
  567. @staticmethod
  568. def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]:
  569. """Collect annotations from kwargs.
  570. Args:
  571. kwargs: Keyword arguments passed to the function.
  572. Returns:
  573. A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
  574. `PydanticMetadata`.
  575. """
  576. metadata: list[Any] = []
  577. general_metadata = {}
  578. for key, value in list(kwargs.items()):
  579. try:
  580. marker = FieldInfo.metadata_lookup[key]
  581. except KeyError:
  582. continue
  583. del kwargs[key]
  584. if value is not None:
  585. if marker is None:
  586. general_metadata[key] = value
  587. else:
  588. metadata.append(marker(value))
  589. if general_metadata:
  590. metadata.append(_fields.pydantic_general_metadata(**general_metadata))
  591. return metadata
  592. @property
  593. def deprecation_message(self) -> str | None:
  594. """The deprecation message to be emitted, or `None` if not set."""
  595. if self.deprecated is None:
  596. return None
  597. if isinstance(self.deprecated, bool):
  598. return 'deprecated' if self.deprecated else None
  599. return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
  600. @property
  601. def default_factory_takes_validated_data(self) -> bool | None:
  602. """Whether the provided default factory callable has a validated data parameter.
  603. Returns `None` if no default factory is set.
  604. """
  605. if self.default_factory is not None:
  606. return _fields.takes_validated_data_argument(self.default_factory)
  607. @overload
  608. def get_default(
  609. self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
  610. ) -> Any: ...
  611. @overload
  612. def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
  613. def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
  614. """Get the default value.
  615. We expose an option for whether to call the default_factory (if present), as calling it may
  616. result in side effects that we want to avoid. However, there are times when it really should
  617. be called (namely, when instantiating a model via `model_construct`).
  618. Args:
  619. call_default_factory: Whether to call the default factory or not.
  620. validated_data: The already validated data to be passed to the default factory.
  621. Returns:
  622. The default value, calling the default factory if requested or `PydanticUndefined` if not set.
  623. """
  624. return _fields.resolve_default_value(
  625. default=self.default,
  626. default_factory=self.default_factory,
  627. validated_data=validated_data,
  628. call_default_factory=call_default_factory,
  629. )
  630. def is_required(self) -> bool:
  631. """Check if the field is required (i.e., does not have a default value or factory).
  632. Returns:
  633. `True` if the field is required, `False` otherwise.
  634. """
  635. return self.default is PydanticUndefined and self.default_factory is None
  636. def rebuild_annotation(self) -> Any:
  637. """Attempts to rebuild the original annotation for use in function signatures.
  638. If metadata is present, it adds it to the original annotation using
  639. `Annotated`. Otherwise, it returns the original annotation as-is.
  640. Note that because the metadata has been flattened, the original annotation
  641. may not be reconstructed exactly as originally provided, e.g. if the original
  642. type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
  643. Returns:
  644. The rebuilt annotation.
  645. """
  646. if not self.metadata:
  647. return self.annotation
  648. else:
  649. # Annotated arguments must be a tuple
  650. return Annotated[(self.annotation, *self.metadata)] # type: ignore
  651. def apply_typevars_map(
  652. self,
  653. typevars_map: Mapping[TypeVar, Any] | None,
  654. globalns: GlobalsNamespace | None = None,
  655. localns: MappingNamespace | None = None,
  656. ) -> None:
  657. """Apply a `typevars_map` to the annotation.
  658. This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
  659. This method applies the `typevars_map` to the annotation in place.
  660. Args:
  661. typevars_map: A dictionary mapping type variables to their concrete types.
  662. globalns: The globals namespace to use during type annotation evaluation.
  663. localns: The locals namespace to use during type annotation evaluation.
  664. See Also:
  665. pydantic._internal._generics.replace_types is used for replacing the typevars with
  666. their concrete types.
  667. """
  668. annotation = _generics.replace_types(self.annotation, typevars_map)
  669. annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns)
  670. self.annotation = annotation
  671. if not evaluated:
  672. self._complete = False
  673. self._original_annotation = self.annotation
  674. def asdict(self) -> _FieldInfoAsDict:
  675. """Return a dictionary representation of the `FieldInfo` instance.
  676. The returned value is a dictionary with three items:
  677. * `annotation`: The type annotation of the field.
  678. * `metadata`: The metadata list.
  679. * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
  680. """
  681. return {
  682. 'annotation': self.annotation,
  683. 'metadata': self.metadata,
  684. 'attributes': {attr: getattr(self, attr) for attr in _Attrs},
  685. }
  686. def _copy(self) -> Self:
  687. """Return a copy of the `FieldInfo` instance."""
  688. # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
  689. # by some third-party libraries with extra attributes defined (and as `FieldInfo`
  690. # is slotted, we can't make a copy of the `__dict__`).
  691. if type(self) is FieldInfo:
  692. # Fast-path if the instance isn't a subclass (`copy.copy()` relies on pickling which is slower):
  693. copied = FieldInfo.__new__(FieldInfo)
  694. for attr_name in FieldInfo.__slots__:
  695. setattr(copied, attr_name, getattr(self, attr_name))
  696. else:
  697. copied = copy(self)
  698. for attr_name in ('metadata', '_attributes_set', '_qualifiers'):
  699. # Apply "deep-copy" behavior on collections attributes:
  700. setattr(copied, attr_name, getattr(copied, attr_name).copy())
  701. return copied # pyright: ignore[reportReturnType]
  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 to generate the default value. The callable can either take 0 arguments
  1245. (in which case it is called as is) or a single argument containing the validated data (the model's
  1246. [`__dict__`][object.__dict__]) and the already initialized private attributes.
  1247. """
  1248. __slots__ = ('default', 'default_factory')
  1249. def __init__(
  1250. self,
  1251. default: Any = PydanticUndefined,
  1252. *,
  1253. default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
  1254. ) -> None:
  1255. if default is Ellipsis:
  1256. self.default = PydanticUndefined
  1257. else:
  1258. self.default = default
  1259. self.default_factory = default_factory
  1260. if not TYPE_CHECKING:
  1261. # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
  1262. def __getattr__(self, item: str) -> Any:
  1263. """This function improves compatibility with custom descriptors by ensuring delegation happens
  1264. as expected when the default value of a private attribute is a descriptor.
  1265. """
  1266. if item in {'__get__', '__set__', '__delete__'}:
  1267. if hasattr(self.default, item):
  1268. return getattr(self.default, item)
  1269. raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
  1270. def __set_name__(self, cls: type[Any], name: str) -> None:
  1271. """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
  1272. default = self.default
  1273. if default is PydanticUndefined:
  1274. return
  1275. set_name = getattr(default, '__set_name__', None)
  1276. if callable(set_name):
  1277. set_name(cls, name)
  1278. @property
  1279. def default_factory_takes_validated_data(self) -> bool | None:
  1280. """Whether the provided default factory callable has a validated data parameter.
  1281. Returns `None` if no default factory is set.
  1282. """
  1283. if self.default_factory is not None:
  1284. return _fields.takes_validated_data_argument(self.default_factory)
  1285. @overload
  1286. def get_default(
  1287. self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
  1288. ) -> Any: ...
  1289. @overload
  1290. def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
  1291. def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
  1292. """Get the default value.
  1293. We expose an option for whether to call the default_factory (if present), as calling it may
  1294. result in side effects that we want to avoid. However, there are times when it really should
  1295. be called (namely, when instantiating a model via `model_construct`).
  1296. Args:
  1297. call_default_factory: Whether to call the default factory or not.
  1298. validated_data: The already validated data to be passed to the default factory.
  1299. Returns:
  1300. The default value, calling the default factory if requested or `None` if not set.
  1301. """
  1302. return _fields.resolve_default_value(
  1303. default=self.default,
  1304. default_factory=self.default_factory,
  1305. validated_data=validated_data,
  1306. call_default_factory=call_default_factory,
  1307. )
  1308. def __eq__(self, other: Any) -> bool:
  1309. return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
  1310. other.default,
  1311. other.default_factory,
  1312. )
  1313. # NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
  1314. # to understand the magic that happens at runtime.
  1315. @overload # `default` argument set
  1316. def PrivateAttr(
  1317. default: _T,
  1318. *,
  1319. init: Literal[False] = False,
  1320. ) -> _T: ...
  1321. @overload # `default_factory` argument set
  1322. def PrivateAttr(
  1323. *,
  1324. default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
  1325. init: Literal[False] = False,
  1326. ) -> _T: ...
  1327. @overload # No default set
  1328. def PrivateAttr(
  1329. *,
  1330. init: Literal[False] = False,
  1331. ) -> Any: ...
  1332. def PrivateAttr(
  1333. default: Any = PydanticUndefined,
  1334. *,
  1335. default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
  1336. init: Literal[False] = False,
  1337. ) -> Any:
  1338. """!!! abstract "Usage Documentation"
  1339. [Private Model Attributes](../concepts/models.md#private-model-attributes)
  1340. Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
  1341. Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
  1342. Private attributes are stored in `__private_attributes__` on the model.
  1343. Args:
  1344. default: The attribute's default value. Defaults to Undefined.
  1345. default_factory: A callable to generate the default value. The callable can either take 0 arguments
  1346. (in which case it is called as is) or a single argument containing the validated data (the model's
  1347. [`__dict__`][object.__dict__]) and the already initialized private attributes.
  1348. If both `default` and `default_factory` are set, an error will be raised.
  1349. init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
  1350. Returns:
  1351. An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
  1352. Raises:
  1353. ValueError: If both `default` and `default_factory` are set.
  1354. """
  1355. if default is not PydanticUndefined and default_factory is not None:
  1356. raise TypeError('cannot specify both default and default_factory')
  1357. return ModelPrivateAttr(
  1358. default,
  1359. default_factory=default_factory,
  1360. )
  1361. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  1362. class ComputedFieldInfo:
  1363. """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
  1364. Attributes:
  1365. decorator_repr: A class variable representing the decorator string, '@computed_field'.
  1366. wrapped_property: The wrapped computed field property.
  1367. return_type: The type of the computed field property's return value.
  1368. alias: The alias of the property to be used during serialization.
  1369. alias_priority: The priority of the alias. This affects whether an alias generator is used.
  1370. title: Title of the computed field to include in the serialization JSON schema.
  1371. field_title_generator: A callable that takes a field name and returns title for it.
  1372. description: Description of the computed field to include in the serialization JSON schema.
  1373. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
  1374. or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
  1375. examples: Example values of the computed field to include in the serialization JSON schema.
  1376. json_schema_extra: A dict or callable to provide extra JSON schema properties.
  1377. repr: A boolean indicating whether to include the field in the __repr__ output.
  1378. """
  1379. decorator_repr: ClassVar[str] = '@computed_field'
  1380. wrapped_property: property
  1381. return_type: Any
  1382. alias: str | None
  1383. alias_priority: int | None
  1384. exclude_if: Callable[[Any], bool] | None
  1385. title: str | None
  1386. field_title_generator: Callable[[str, ComputedFieldInfo], str] | None
  1387. description: str | None
  1388. deprecated: Deprecated | str | bool | None
  1389. examples: list[Any] | None
  1390. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
  1391. repr: bool
  1392. # NOTE: if you add a new field, add it to the `__copy__()` implementation.
  1393. def __copy__(self) -> Self:
  1394. return type(self)(
  1395. wrapped_property=self.wrapped_property,
  1396. return_type=self.return_type,
  1397. alias=self.alias,
  1398. alias_priority=self.alias_priority,
  1399. exclude_if=self.exclude_if,
  1400. title=self.title,
  1401. field_title_generator=self.field_title_generator,
  1402. description=self.description,
  1403. deprecated=self.deprecated,
  1404. examples=self.examples.copy() if isinstance(self.examples, list) else self.examples,
  1405. json_schema_extra=self.json_schema_extra.copy()
  1406. if isinstance(self.json_schema_extra, dict)
  1407. else self.json_schema_extra,
  1408. repr=self.repr,
  1409. )
  1410. @property
  1411. def deprecation_message(self) -> str | None:
  1412. """The deprecation message to be emitted, or `None` if not set."""
  1413. if self.deprecated is None:
  1414. return None
  1415. if isinstance(self.deprecated, bool):
  1416. return 'deprecated' if self.deprecated else None
  1417. return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
  1418. def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None:
  1419. """Update the instance from the configuration set on the class this computed field belongs to."""
  1420. title_generator = self.field_title_generator or config_wrapper.field_title_generator
  1421. if title_generator is not None and self.title is None:
  1422. self.title = title_generator(name, self)
  1423. if config_wrapper.alias_generator is not None:
  1424. self._apply_alias_generator(config_wrapper.alias_generator, name)
  1425. def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None:
  1426. """Apply an alias generator to aliases if appropriate.
  1427. Args:
  1428. alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
  1429. name: The name of the computed field from which to generate the alias.
  1430. """
  1431. # Apply an alias_generator if
  1432. # 1. An alias is not specified
  1433. # 2. An alias is specified, but the priority is <= 1
  1434. if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None:
  1435. alias, _, serialization_alias = None, None, None
  1436. if isinstance(alias_generator, AliasGenerator):
  1437. alias, _, serialization_alias = alias_generator.generate_aliases(name)
  1438. elif callable(alias_generator):
  1439. alias = alias_generator(name)
  1440. # if priority is not set, we set to 1
  1441. # which supports the case where the alias_generator from a child class is used
  1442. # to generate an alias for a field in a parent class
  1443. if self.alias_priority is None or self.alias_priority <= 1:
  1444. self.alias_priority = 1
  1445. # if the priority is 1, then we set the aliases to the generated alias
  1446. # note that we use the serialization_alias with priority over alias, as computed_field
  1447. # aliases are used for serialization only (not validation)
  1448. if self.alias_priority == 1:
  1449. self.alias = _utils.get_first_not_none(serialization_alias, alias)
  1450. def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore
  1451. """Returns true if provided property is private, False otherwise."""
  1452. wrapped_name: str = ''
  1453. if isinstance(property_, property):
  1454. wrapped_name = getattr(property_.fget, '__name__', '')
  1455. elif isinstance(property_, cached_property): # type: ignore
  1456. wrapped_name = getattr(property_.func, '__name__', '') # type: ignore
  1457. return wrapped_name.startswith('_') and not wrapped_name.startswith('__')
  1458. # this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
  1459. # See https://github.com/python/typing/issues/985 and linked issues
  1460. PropertyT = TypeVar('PropertyT')
  1461. @overload
  1462. def computed_field(func: PropertyT, /) -> PropertyT: ...
  1463. @overload
  1464. def computed_field(
  1465. *,
  1466. alias: str | None = None,
  1467. alias_priority: int | None = None,
  1468. exclude_if: Callable[[Any], bool] | None = None,
  1469. title: str | None = None,
  1470. field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
  1471. description: str | None = None,
  1472. deprecated: Deprecated | str | bool | None = None,
  1473. examples: list[Any] | None = None,
  1474. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
  1475. repr: bool = True,
  1476. return_type: Any = PydanticUndefined,
  1477. ) -> Callable[[PropertyT], PropertyT]: ...
  1478. def computed_field(
  1479. func: PropertyT | None = None,
  1480. /,
  1481. *,
  1482. alias: str | None = None,
  1483. alias_priority: int | None = None,
  1484. exclude_if: Callable[[Any], bool] | None = None,
  1485. title: str | None = None,
  1486. field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
  1487. description: str | None = None,
  1488. deprecated: Deprecated | str | bool | None = None,
  1489. examples: list[Any] | None = None,
  1490. json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
  1491. repr: bool | None = None,
  1492. return_type: Any = PydanticUndefined,
  1493. ) -> PropertyT | Callable[[PropertyT], PropertyT]:
  1494. """!!! abstract "Usage Documentation"
  1495. [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
  1496. Decorator to include `property` and `cached_property` when serializing models or dataclasses.
  1497. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
  1498. ```python
  1499. from pydantic import BaseModel, computed_field
  1500. class Rectangle(BaseModel):
  1501. width: int
  1502. length: int
  1503. @computed_field
  1504. @property
  1505. def area(self) -> int:
  1506. return self.width * self.length
  1507. print(Rectangle(width=3, length=2).model_dump())
  1508. #> {'width': 3, 'length': 2, 'area': 6}
  1509. ```
  1510. If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
  1511. automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
  1512. and confuse static type checkers, thus explicit use of `@property` is recommended.
  1513. !!! warning "Mypy Warning"
  1514. Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
  1515. mypy may throw a `Decorated property not supported` error.
  1516. See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
  1517. To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
  1518. [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
  1519. ```python
  1520. import random
  1521. from pydantic import BaseModel, computed_field
  1522. class Square(BaseModel):
  1523. width: float
  1524. @computed_field
  1525. def area(self) -> float: # converted to a `property` by `computed_field`
  1526. return round(self.width**2, 2)
  1527. @area.setter
  1528. def area(self, new_area: float) -> None:
  1529. self.width = new_area**0.5
  1530. @computed_field(alias='the magic number', repr=False)
  1531. def random_number(self) -> int:
  1532. return random.randint(0, 1_000)
  1533. square = Square(width=1.3)
  1534. # `random_number` does not appear in representation
  1535. print(repr(square))
  1536. #> Square(width=1.3, area=1.69)
  1537. print(square.random_number)
  1538. #> 3
  1539. square.area = 4
  1540. print(square.model_dump_json(by_alias=True))
  1541. #> {"width":2.0,"area":4.0,"the magic number":3}
  1542. ```
  1543. !!! warning "Overriding with `computed_field`"
  1544. You can't override a field from a parent class with a `computed_field` in the child class.
  1545. `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
  1546. See the example below:
  1547. ```python
  1548. from pydantic import BaseModel, computed_field
  1549. class Parent(BaseModel):
  1550. a: str
  1551. try:
  1552. class Child(Parent):
  1553. @computed_field
  1554. @property
  1555. def a(self) -> str:
  1556. return 'new a'
  1557. except TypeError as e:
  1558. print(e)
  1559. '''
  1560. Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
  1561. '''
  1562. ```
  1563. Private properties decorated with `@computed_field` have `repr=False` by default.
  1564. ```python
  1565. from functools import cached_property
  1566. from pydantic import BaseModel, computed_field
  1567. class Model(BaseModel):
  1568. foo: int
  1569. @computed_field
  1570. @cached_property
  1571. def _private_cached_property(self) -> int:
  1572. return -self.foo
  1573. @computed_field
  1574. @property
  1575. def _private_property(self) -> int:
  1576. return -self.foo
  1577. m = Model(foo=1)
  1578. print(repr(m))
  1579. #> Model(foo=1)
  1580. ```
  1581. Args:
  1582. func: the function to wrap.
  1583. alias: alias to use when serializing this computed field, only used when `by_alias=True`
  1584. alias_priority: priority of the alias. This affects whether an alias generator is used
  1585. exclude_if: A callable that determines whether to exclude this computed field during serialization based on its value.
  1586. title: Title to use when including this computed field in JSON Schema
  1587. field_title_generator: A callable that takes a field name and returns title for it.
  1588. description: Description to use when including this computed field in JSON Schema, defaults to the function's
  1589. docstring
  1590. deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
  1591. to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
  1592. `deprecated` decorator.
  1593. examples: Example values to use when including this computed field in JSON Schema
  1594. json_schema_extra: A dict or callable to provide extra JSON schema properties.
  1595. repr: whether to include this computed field in model repr.
  1596. Default is `False` for private properties and `True` for public properties.
  1597. return_type: optional return for serialization logic to expect when serializing to JSON, if included
  1598. this must be correct, otherwise a `TypeError` is raised.
  1599. If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
  1600. objects.
  1601. Returns:
  1602. A proxy wrapper for the property.
  1603. """
  1604. def dec(f: Any) -> Any:
  1605. nonlocal description, deprecated, return_type, alias_priority
  1606. unwrapped = _decorators.unwrap_wrapped_function(f)
  1607. if description is None and unwrapped.__doc__:
  1608. description = inspect.cleandoc(unwrapped.__doc__)
  1609. if deprecated is None and hasattr(unwrapped, '__deprecated__'):
  1610. deprecated = unwrapped.__deprecated__
  1611. # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
  1612. f = _decorators.ensure_property(f)
  1613. alias_priority = (alias_priority or 2) if alias is not None else None
  1614. if repr is None:
  1615. repr_: bool = not _wrapped_property_is_private(property_=f)
  1616. else:
  1617. repr_ = repr
  1618. dec_info = ComputedFieldInfo(
  1619. f,
  1620. return_type,
  1621. alias,
  1622. alias_priority,
  1623. exclude_if,
  1624. title,
  1625. field_title_generator,
  1626. description,
  1627. deprecated,
  1628. examples,
  1629. json_schema_extra,
  1630. repr_,
  1631. )
  1632. return _decorators.PydanticDescriptorProxy(f, dec_info)
  1633. if func is None:
  1634. return dec
  1635. else:
  1636. return dec(func)