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