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 types import EllipsisType
14from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, TypeAlias, TypeVar, final, overload
15from warnings import warn
17import annotated_types
18import typing_extensions
19from pydantic_core import MISSING, PydanticUndefined
20from typing_extensions import Self, TypedDict, TypeForm, Unpack, deprecated
21from typing_inspection import typing_objects
22from typing_inspection.introspection import UNKNOWN, AnnotationSource, ForbiddenQualifier, Qualifier, inspect_annotation
24from . import types
25from ._internal import _decorators, _fields, _generics, _repr, _typing_extra, _utils
26from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace
27from .aliases import AliasChoices, AliasGenerator, AliasPath
28from .config import JsonDict
29from .errors import PydanticForbiddenQualifier, PydanticUserError
30from .json_schema import PydanticJsonSchemaWarning
31from .warnings import PydanticDeprecatedSince20
33if TYPE_CHECKING:
34 from ._internal._config import ConfigWrapper
35 from ._internal._repr import ReprArgs
38__all__ = 'Field', 'FieldInfo', 'PrivateAttr', 'computed_field'
41_Unset: Any = PydanticUndefined
43if sys.version_info >= (3, 13):
44 import warnings
46 Deprecated: TypeAlias = warnings.deprecated | deprecated
47else:
48 Deprecated: TypeAlias = deprecated
51class _FromFieldInfoInputs(TypedDict, total=False):
52 """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
54 annotation: TypeForm[Any]
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 _FieldInfoAsDict(TypedDict, closed=True):
93 annotation: TypeForm[Any] | None
94 metadata: list[Any]
95 attributes: dict[str, 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 The `FieldInfo` class is meant to expose information about a field in a Pydantic model or dataclass.
107 `FieldInfo` instances shouldn't be instantiated directly, nor mutated.
109 If you need to derive a new model from another one and are willing to alter `FieldInfo` instances,
110 refer to this [dynamic model example](../examples/dynamic_models.md).
112 Attributes:
113 annotation: The type annotation of the field.
114 default: The default value of the field.
115 default_factory: A callable to generate the default value. The callable can either take 0 arguments
116 (in which case it is called as is) or a single argument containing the already validated data.
117 alias: The alias name of the field.
118 alias_priority: The priority of the field's alias.
119 validation_alias: The validation alias of the field.
120 serialization_alias: The serialization alias of the field.
121 title: The title of the field.
122 field_title_generator: A callable that takes a field's name and info and returns title for it.
123 description: The description of the field.
124 examples: List of examples of the field.
125 exclude: Whether to exclude the field from the model serialization.
126 exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
127 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
128 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
129 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
130 json_schema_extra: A dict or callable to provide extra JSON schema properties.
131 frozen: Whether the field is frozen.
132 validate_default: Whether to validate the default value of the field.
133 repr: Whether to include the field in representation of the model.
134 init: Whether the field should be included in the constructor of the dataclass.
135 init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
136 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
137 metadata: The metadata list. Contains all the data that isn't expressed as direct `FieldInfo` attributes, including:
139 * Type-specific constraints, such as `gt` or `min_length` (these are converted to metadata classes such as `annotated_types.Gt`).
140 * Any other arbitrary object used within [`Annotated`][typing.Annotated] metadata
141 (e.g. [custom types handlers](../concepts/types.md#as-an-annotation) or any object not recognized by Pydantic).
142 """
144 annotation: TypeForm[Any] | None
145 default: Any
146 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
147 alias: str | None
148 alias_priority: int | None
149 validation_alias: str | AliasPath | AliasChoices | None
150 serialization_alias: str | None
151 title: str | None
152 field_title_generator: Callable[[str, FieldInfo], str] | None
153 description: str | None
154 examples: list[Any] | None
155 exclude: bool | None
156 exclude_if: Callable[[Any], bool] | None
157 discriminator: str | types.Discriminator | None
158 deprecated: Deprecated | str | bool | None
159 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
160 frozen: bool | None
161 validate_default: bool | None
162 repr: bool
163 init: bool | None
164 init_var: bool | None
165 kw_only: bool | None
166 metadata: list[Any]
168 __slots__ = (
169 'annotation',
170 'default',
171 'default_factory',
172 'alias',
173 'alias_priority',
174 'validation_alias',
175 'serialization_alias',
176 'title',
177 'field_title_generator',
178 'description',
179 'examples',
180 'exclude',
181 'exclude_if',
182 'discriminator',
183 'deprecated',
184 'json_schema_extra',
185 'frozen',
186 'validate_default',
187 'repr',
188 'init',
189 'init_var',
190 'kw_only',
191 'metadata',
192 '_attributes_set',
193 '_qualifiers',
194 '_complete',
195 '_original_assignment',
196 '_original_annotation',
197 '_final',
198 )
200 # used to convert kwargs to metadata/constraints,
201 # None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
202 metadata_lookup: ClassVar[dict[str, Callable[[Any], Any] | None]] = {
203 'strict': types.Strict,
204 'gt': annotated_types.Gt,
205 'ge': annotated_types.Ge,
206 'lt': annotated_types.Lt,
207 'le': annotated_types.Le,
208 'multiple_of': annotated_types.MultipleOf,
209 'min_length': annotated_types.MinLen,
210 'max_length': annotated_types.MaxLen,
211 'pattern': None,
212 'allow_inf_nan': types.AllowInfNan,
213 'max_digits': None,
214 'decimal_places': None,
215 'union_mode': None,
216 'coerce_numbers_to_str': None,
217 'fail_fast': types.FailFast,
218 }
220 def __init__(
221 self,
222 *,
223 annotation: TypeForm[Any] | None = _Unset,
224 default: Any = _Unset,
225 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
226 alias: str | None = _Unset,
227 alias_priority: int | None = _Unset,
228 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
229 serialization_alias: str | None = _Unset,
230 title: str | None = _Unset,
231 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
232 description: str | None = _Unset,
233 examples: list[Any] | None = _Unset,
234 exclude: bool | None = _Unset,
235 exclude_if: Callable[[Any], bool] | None = _Unset,
236 discriminator: str | types.Discriminator | None = _Unset,
237 deprecated: Deprecated | str | bool | None = _Unset,
238 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
239 frozen: bool | None = _Unset,
240 validate_default: bool | None = _Unset,
241 repr: bool = _Unset,
242 init: bool | None = _Unset,
243 init_var: bool | None = _Unset,
244 kw_only: bool | None = _Unset,
245 # The following arguments are converted to metadata (see `_collect_metadata()`), in the order `Field()` forwards them:
246 pattern: str | re.Pattern[str] | None = _Unset,
247 coerce_numbers_to_str: bool | None = _Unset,
248 strict: bool | None = _Unset,
249 gt: annotated_types.SupportsGt | None = _Unset,
250 ge: annotated_types.SupportsGe | None = _Unset,
251 lt: annotated_types.SupportsLt | None = _Unset,
252 le: annotated_types.SupportsLe | None = _Unset,
253 multiple_of: float | None = _Unset,
254 min_length: int | None = _Unset,
255 max_length: int | None = _Unset,
256 allow_inf_nan: bool | None = _Unset,
257 max_digits: int | None = _Unset,
258 decimal_places: int | None = _Unset,
259 union_mode: Literal['smart', 'left_to_right'] | None = _Unset,
260 fail_fast: bool | None = _Unset,
261 **kwargs: Any,
262 ) -> None:
263 """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
264 or one of the constructor classmethods.
266 See the signature of `pydantic.fields.Field` for more details about the expected arguments.
267 Unknown keyword arguments are accepted (and ignored) for backwards compatibility.
268 """
269 # Tracking the explicitly set attributes is necessary to correctly merge `Field()` functions
270 # (e.g. with `Annotated[int, Field(alias='a'), Field(alias=None)]`, even though `None` is the default value,
271 # we need to track that `alias=None` was explicitly set):
272 self._attributes_set = attributes_set = {}
274 if annotation is _Unset:
275 annotation = None
276 else:
277 attributes_set['annotation'] = annotation
278 self.annotation = annotation
280 if default is _Unset or default is Ellipsis:
281 default = PydanticUndefined
282 else:
283 attributes_set['default'] = default
284 self.default = default
286 if default_factory is _Unset:
287 default_factory = None
288 else:
289 attributes_set['default_factory'] = default_factory
290 self.default_factory = default_factory
292 if default is not PydanticUndefined and default_factory is not None:
293 raise TypeError('cannot specify both default and default_factory')
295 if alias is _Unset:
296 alias = None
297 else:
298 attributes_set['alias'] = alias
299 self.alias = alias
301 if alias_priority is _Unset:
302 alias_priority = None
303 else:
304 attributes_set['alias_priority'] = alias_priority
306 if validation_alias is _Unset:
307 validation_alias = None
308 else:
309 attributes_set['validation_alias'] = validation_alias
310 self.validation_alias = validation_alias
312 if serialization_alias is _Unset:
313 serialization_alias = None
314 else:
315 attributes_set['serialization_alias'] = serialization_alias
316 self.serialization_alias = serialization_alias
318 alias_is_set = alias is not None or validation_alias is not None or serialization_alias is not None
319 self.alias_priority = (alias_priority or 2) if alias_is_set else None
321 if title is _Unset:
322 title = None
323 else:
324 attributes_set['title'] = title
325 self.title = title
327 if field_title_generator is _Unset:
328 field_title_generator = None
329 else:
330 attributes_set['field_title_generator'] = field_title_generator
331 self.field_title_generator = field_title_generator
333 if description is _Unset:
334 description = None
335 else:
336 attributes_set['description'] = description
337 self.description = description
339 if examples is _Unset:
340 examples = None
341 else:
342 attributes_set['examples'] = examples
343 self.examples = examples
345 if exclude is _Unset:
346 exclude = None
347 else:
348 attributes_set['exclude'] = exclude
349 self.exclude = exclude
351 if exclude_if is _Unset:
352 exclude_if = None
353 else:
354 attributes_set['exclude_if'] = exclude_if
355 self.exclude_if = exclude_if
357 if discriminator is _Unset:
358 discriminator = None
359 else:
360 attributes_set['discriminator'] = discriminator
361 self.discriminator = discriminator
363 if deprecated is _Unset:
364 # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
365 deprecated = getattr(self, 'deprecated', None)
366 else:
367 attributes_set['deprecated'] = deprecated
368 self.deprecated = deprecated
370 if repr is _Unset:
371 repr = True
372 else:
373 attributes_set['repr'] = repr
374 self.repr = repr
376 if json_schema_extra is _Unset:
377 json_schema_extra = None
378 else:
379 attributes_set['json_schema_extra'] = json_schema_extra
380 self.json_schema_extra = json_schema_extra
382 if validate_default is _Unset:
383 validate_default = None
384 else:
385 attributes_set['validate_default'] = validate_default
386 self.validate_default = validate_default
388 if frozen is _Unset:
389 frozen = None
390 else:
391 attributes_set['frozen'] = frozen
392 self.frozen = frozen
394 # currently only used on dataclasses
395 if init is _Unset:
396 init = None
397 else:
398 attributes_set['init'] = init
399 self.init = init
401 if init_var is _Unset:
402 init_var = None
403 else:
404 attributes_set['init_var'] = init_var
405 self.init_var = init_var
407 if kw_only is _Unset:
408 kw_only = None
409 else:
410 attributes_set['kw_only'] = kw_only
411 self.kw_only = kw_only
413 # (in the order `Field()` forwards them, which determines the order of the metadata)
414 metadata_kwargs: dict[str, Any] = {}
415 if pattern is not _Unset:
416 metadata_kwargs['pattern'] = pattern
417 if coerce_numbers_to_str is not _Unset:
418 metadata_kwargs['coerce_numbers_to_str'] = coerce_numbers_to_str
419 if strict is not _Unset:
420 metadata_kwargs['strict'] = strict
421 if gt is not _Unset:
422 metadata_kwargs['gt'] = gt
423 if ge is not _Unset:
424 metadata_kwargs['ge'] = ge
425 if lt is not _Unset:
426 metadata_kwargs['lt'] = lt
427 if le is not _Unset:
428 metadata_kwargs['le'] = le
429 if multiple_of is not _Unset:
430 metadata_kwargs['multiple_of'] = multiple_of
431 if min_length is not _Unset:
432 metadata_kwargs['min_length'] = min_length
433 if max_length is not _Unset:
434 metadata_kwargs['max_length'] = max_length
435 if allow_inf_nan is not _Unset:
436 metadata_kwargs['allow_inf_nan'] = allow_inf_nan
437 if max_digits is not _Unset:
438 metadata_kwargs['max_digits'] = max_digits
439 if decimal_places is not _Unset:
440 metadata_kwargs['decimal_places'] = decimal_places
441 if union_mode is not _Unset:
442 metadata_kwargs['union_mode'] = union_mode
443 if fail_fast is not _Unset:
444 metadata_kwargs['fail_fast'] = fail_fast
445 self.metadata = self._collect_metadata(metadata_kwargs) if metadata_kwargs else []
447 if kwargs:
448 # Unknown keyword arguments (kept for backwards compatibility):
449 attributes_set.update({key: value for key, value in kwargs.items() if value is not _Unset})
451 # Private attributes:
452 self._qualifiers: set[Qualifier] = set()
453 # Used to rebuild FieldInfo instances:
454 self._complete = True
455 self._original_annotation: Any = PydanticUndefined
456 self._original_assignment: Any = PydanticUndefined
457 # Used to track whether the `FieldInfo` instance represents the data about a field (and is exposed in `model_fields`/`__pydantic_fields__`),
458 # or if it is the result of the `Field()` function being used as metadata in an `Annotated` type/as an assignment
459 # (not an ideal pattern, see https://github.com/pydantic/pydantic/issues/11122):
460 self._final = False
462 @staticmethod
463 def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo:
464 """Create a new `FieldInfo` object with the `Field` function.
466 Args:
467 default: The default value for the field. Defaults to Undefined.
468 **kwargs: Additional arguments dictionary.
470 Raises:
471 TypeError: If 'annotation' is passed as a keyword argument.
473 Returns:
474 A new FieldInfo object with the given parameters.
476 Example:
477 This is how you can create a field with default value like this:
479 ```python
480 import pydantic
482 class MyModel(pydantic.BaseModel):
483 foo: int = pydantic.Field(4)
484 ```
485 """
486 if 'annotation' in kwargs:
487 raise TypeError('"annotation" is not permitted as a Field keyword argument')
488 return FieldInfo(default=default, **kwargs)
490 @staticmethod
491 def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo:
492 """Creates a `FieldInfo` instance from a bare annotation.
494 This function is used internally to create a `FieldInfo` from a bare annotation like this:
496 ```python
497 import pydantic
499 class MyModel(pydantic.BaseModel):
500 foo: int # <-- like this
501 ```
503 We also account for the case where the annotation can be an instance of `Annotated` and where
504 one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
506 ```python
507 from typing import Annotated
509 import annotated_types
511 import pydantic
513 class MyModel(pydantic.BaseModel):
514 foo: Annotated[int, annotated_types.Gt(42)]
515 bar: Annotated[int, pydantic.Field(gt=42)]
516 ```
518 Args:
519 annotation: An annotation object.
521 Returns:
522 An instance of the field metadata.
523 """
524 try:
525 inspected_ann = inspect_annotation(
526 annotation,
527 annotation_source=_source,
528 unpack_type_aliases='skip',
529 )
530 except ForbiddenQualifier as e:
531 raise PydanticForbiddenQualifier(e.qualifier, annotation)
533 # TODO check for classvar and error?
535 # No assigned value, this happens when using a bare `Final` qualifier (also for other
536 # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
537 # because we don't have any assigned value.
538 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
539 final = 'final' in inspected_ann.qualifiers
540 metadata = inspected_ann.metadata
542 attr_overrides = {'annotation': type_expr}
543 if final:
544 attr_overrides['frozen'] = True
545 field_info = FieldInfo._construct(metadata, **attr_overrides)
546 field_info._qualifiers = inspected_ann.qualifiers
547 field_info._final = True
548 return field_info
550 @staticmethod
551 def from_annotated_attribute(
552 annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
553 ) -> FieldInfo:
554 """Create `FieldInfo` from an annotation with a default value.
556 This is used in cases like the following:
558 ```python
559 from typing import Annotated
561 import annotated_types
563 import pydantic
565 class MyModel(pydantic.BaseModel):
566 foo: int = 4 # <-- like this
567 bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
568 spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
569 ```
571 Args:
572 annotation: The type annotation of the field.
573 default: The default value of the field.
575 Returns:
576 A field object with the passed values.
577 """
578 if annotation is not MISSING and annotation is default:
579 raise PydanticUserError(
580 'Error when building FieldInfo from annotated attribute. '
581 "Make sure you don't have any field name clashing with a type annotation.",
582 code='unevaluable-type-annotation',
583 )
585 try:
586 inspected_ann = inspect_annotation(
587 annotation,
588 annotation_source=_source,
589 unpack_type_aliases='skip',
590 )
591 except ForbiddenQualifier as e:
592 raise PydanticForbiddenQualifier(e.qualifier, annotation)
594 # TODO check for classvar and error?
596 # TODO infer from the default, this can be done in v3 once we treat final fields with
597 # a default as proper fields and not class variables:
598 type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
599 final = 'final' in inspected_ann.qualifiers
600 metadata = inspected_ann.metadata
602 # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend
603 # metadata from the assignment at the beginning of the metadata. Changing this is only
604 # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507
605 prepend_metadata: list[Any] | None = None
606 attr_overrides = {'annotation': type_expr}
607 if final:
608 attr_overrides['frozen'] = True
610 # HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
611 # instance's type to be preserved when constructing new models with its subclasses as assignments.
612 # This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
613 if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo:
614 field_info = default._copy()
615 field_info._attributes_set.update(attr_overrides)
616 for k, v in attr_overrides.items():
617 setattr(field_info, k, v)
618 return field_info
620 if isinstance(default, FieldInfo):
621 default_copy = default._copy() # Copy unnecessary when we remove HACK 1.
622 prepend_metadata = default_copy.metadata
623 default_copy.metadata = []
624 metadata = metadata + [default_copy]
625 if 'init_var' in inspected_ann.qualifiers:
626 # Only relevant for dataclasses, when `f: InitVar[<type>] = Field(...)`
627 # is used:
628 attr_overrides['init_var'] = True
629 elif isinstance(default, dataclasses.Field):
630 from_field = FieldInfo._from_dataclass_field(default)
631 prepend_metadata = from_field.metadata # Unnecessary when we remove HACK 1.
632 from_field.metadata = []
633 metadata = metadata + [from_field]
634 if 'init_var' in inspected_ann.qualifiers:
635 attr_overrides['init_var'] = True
636 if (init := getattr(default, 'init', None)) is not None:
637 attr_overrides['init'] = init
638 if (kw_only := getattr(default, 'kw_only', None)) is not None:
639 attr_overrides['kw_only'] = kw_only
640 else:
641 # `default` is the actual default value
642 attr_overrides['default'] = default
644 field_info = FieldInfo._construct(
645 prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
646 )
647 field_info._qualifiers = inspected_ann.qualifiers
648 field_info._final = True
649 return field_info
651 @classmethod
652 def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self:
653 """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata.
655 With the following example:
657 ```python {test="skip" lint="skip"}
658 class Model(BaseModel):
659 f: Annotated[int, Gt(1), Field(description='desc', lt=2)]
660 ```
662 `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right:
664 - If the element is a `Field()` function (which is itself a `FieldInfo` instance), the field attributes (such as
665 `description`) are saved to be set on the final `FieldInfo` instance.
666 On the other hand, some kwargs (such as `lt`) are stored as `metadata` (see `FieldInfo.__init__()`, calling
667 `FieldInfo._collect_metadata()`). In this case, the final metadata list is extended with the one from this instance.
668 - Else, the element is considered as a single metadata object, and is appended to the final metadata list.
670 Args:
671 metadata: The list of metadata elements to merge together. If the `FieldInfo` instance to be constructed is for
672 a field with an assigned `Field()`, this `Field()` assignment should be added as the last element of the
673 provided metadata.
674 **attr_overrides: Extra attributes that should be set on the final merged `FieldInfo` instance.
676 Returns:
677 The final merged `FieldInfo` instance.
678 """
679 merged_metadata: list[Any] = []
680 merged_kwargs: dict[str, Any] = {}
682 for meta in metadata:
683 if isinstance(meta, FieldInfo):
684 merged_metadata.extend(meta.metadata)
686 new_js_extra: JsonDict | None = None
687 current_js_extra = meta.json_schema_extra
688 if current_js_extra is not None and 'json_schema_extra' in merged_kwargs:
689 # We need to merge `json_schema_extra`'s:
690 existing_js_extra = merged_kwargs['json_schema_extra']
691 if isinstance(existing_js_extra, dict):
692 if isinstance(current_js_extra, dict):
693 new_js_extra = {
694 **existing_js_extra,
695 **current_js_extra,
696 }
697 elif callable(current_js_extra):
698 # The `callable` is ignored, so we keep the existing `dict`. This needs to be set
699 # explicitly as `merged_kwargs` is otherwise overridden with `meta._attributes_set`
700 # (which contains the `callable`) below.
701 new_js_extra = existing_js_extra
702 warn(
703 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
704 'The `callable` type is being ignored. '
705 "If you'd like support for this behavior, please open an issue on pydantic.",
706 UserWarning,
707 )
708 elif callable(existing_js_extra) and isinstance(current_js_extra, dict):
709 warn(
710 'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
711 'The `callable` type is being ignored. '
712 "If you'd like support for this behavior, please open an issue on pydantic.",
713 UserWarning,
714 )
716 # HACK: It is common for users to define "make model partial" (or similar) utilities, that
717 # convert all model fields to be optional (i.e. have a default value). To do so, they mutate
718 # each `FieldInfo` instance from `model_fields` to set a `default`, and use `create_model()`
719 # with `Annotated[<orig_type> | None, mutated_field_info]`` as an annotation. However, such
720 # mutations (by doing simple assignments) are only accidentally working, because we also
721 # need to track attributes explicitly set in `_attributes_set` (relying on default values for
722 # each attribute is *not* enough, for instance with `Annotated[int, Field(alias='a'), Field(alias=None)]`
723 # the resulting `FieldInfo` should have `alias=None`).
724 # To mitigate this, we add a special case when a "final" `FieldInfo` instance (that is an instance coming
725 # from `model_fields`) is used in annotated metadata (or assignment). In this case, we assume *all* attributes
726 # were explicitly set, and as such we use all of them (and this will correctly pick up the mutations).
727 # In theory, this shouldn't really be supported, you are only supposed to use the `Field()` function, not
728 # a `FieldInfo` instance directly (granted, `Field()` returns a `FieldInfo`, see
729 # https://github.com/pydantic/pydantic/issues/11122):
730 if meta._final:
731 merged_kwargs.update({attr: getattr(meta, attr) for attr in _Attrs})
732 else:
733 merged_kwargs.update(meta._attributes_set)
735 if new_js_extra is not None:
736 merged_kwargs['json_schema_extra'] = new_js_extra
737 elif typing_objects.is_deprecated(meta):
738 merged_kwargs['deprecated'] = meta
739 else:
740 merged_metadata.append(meta)
742 merged_kwargs.update(attr_overrides)
743 merged_field_info = cls(**merged_kwargs)
744 merged_field_info.metadata = merged_metadata
745 return merged_field_info
747 @staticmethod
748 @typing_extensions.deprecated(
749 "The 'merge_field_infos()' method is deprecated and will be removed in a future version. "
750 'If you relied on this method, please open an issue in the Pydantic issue tracker.',
751 category=None,
752 )
753 def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
754 """Merge `FieldInfo` instances keeping only explicitly set attributes.
756 Later `FieldInfo` instances override earlier ones.
758 Returns:
759 FieldInfo: A merged FieldInfo instance.
760 """
761 if len(field_infos) == 1:
762 # No merging necessary, but we still need to make a copy and apply the overrides
763 field_info = field_infos[0]._copy()
764 field_info._attributes_set.update(overrides)
766 default_override = overrides.pop('default', PydanticUndefined)
767 if default_override is Ellipsis:
768 default_override = PydanticUndefined
769 if default_override is not PydanticUndefined:
770 field_info.default = default_override
772 for k, v in overrides.items():
773 setattr(field_info, k, v)
774 return field_info # type: ignore
776 merged_field_info_kwargs: dict[str, Any] = {}
777 metadata = {}
778 for field_info in field_infos:
779 attributes_set = field_info._attributes_set.copy()
781 try:
782 json_schema_extra = attributes_set.pop('json_schema_extra')
783 existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra')
785 if existing_json_schema_extra is None:
786 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
787 if isinstance(existing_json_schema_extra, dict):
788 if isinstance(json_schema_extra, dict):
789 merged_field_info_kwargs['json_schema_extra'] = {
790 **existing_json_schema_extra,
791 **json_schema_extra,
792 }
793 if callable(json_schema_extra):
794 warn(
795 'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
796 'The `callable` type is being ignored.'
797 "If you'd like support for this behavior, please open an issue on pydantic.",
798 PydanticJsonSchemaWarning,
799 )
800 elif callable(json_schema_extra):
801 # if ever there's a case of a callable, we'll just keep the last json schema extra spec
802 merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
803 except KeyError:
804 pass
806 # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
807 merged_field_info_kwargs.update(attributes_set)
809 for x in field_info.metadata:
810 if not isinstance(x, FieldInfo):
811 metadata[type(x)] = x
813 merged_field_info_kwargs.update(overrides)
814 field_info = FieldInfo(**merged_field_info_kwargs)
815 field_info.metadata = list(metadata.values())
816 return field_info
818 @staticmethod
819 def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo:
820 """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
822 Args:
823 dc_field: The `dataclasses.Field` instance to convert.
825 Returns:
826 The corresponding `FieldInfo` instance.
828 Raises:
829 TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
830 """
831 default = dc_field.default
832 if default is dataclasses.MISSING:
833 default = _Unset
835 if dc_field.default_factory is dataclasses.MISSING:
836 default_factory = _Unset
837 else:
838 default_factory = dc_field.default_factory
840 # use the `Field` function so in correct kwargs raise the correct `TypeError`
841 dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES}
842 if sys.version_info >= (3, 14) and dc_field.doc is not None:
843 dc_field_metadata['description'] = dc_field.doc
844 return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) # pyright: ignore[reportCallIssue]
846 @staticmethod
847 def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]:
848 """Collect annotations from kwargs.
850 Args:
851 kwargs: Keyword arguments passed to the function.
853 Returns:
854 A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
855 `PydanticMetadata`.
856 """
857 metadata: list[Any] = []
858 general_metadata = {}
859 for key, value in list(kwargs.items()):
860 try:
861 marker = FieldInfo.metadata_lookup[key]
862 except KeyError:
863 continue
865 del kwargs[key]
866 if value is not None:
867 if marker is None:
868 general_metadata[key] = value
869 else:
870 metadata.append(marker(value))
871 if general_metadata:
872 metadata.append(_fields.pydantic_general_metadata(**general_metadata))
873 return metadata
875 @property
876 def deprecation_message(self) -> str | None:
877 """The deprecation message to be emitted, or `None` if not set."""
878 if self.deprecated is None:
879 return None
880 if isinstance(self.deprecated, bool):
881 return 'deprecated' if self.deprecated else None
882 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
884 @property
885 def default_factory_takes_validated_data(self) -> bool | None:
886 """Whether the provided default factory callable has a validated data parameter.
888 Returns `None` if no default factory is set.
889 """
890 if self.default_factory is not None:
891 return _fields.takes_validated_data_argument(self.default_factory)
893 @overload
894 def get_default(
895 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
896 ) -> Any: ...
898 @overload
899 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
901 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
902 """Get the default value.
904 We expose an option for whether to call the default_factory (if present), as calling it may
905 result in side effects that we want to avoid. However, there are times when it really should
906 be called (namely, when instantiating a model via `model_construct`).
908 Args:
909 call_default_factory: Whether to call the default factory or not.
910 validated_data: The already validated data to be passed to the default factory.
912 Returns:
913 The default value, calling the default factory if requested or `PydanticUndefined` if not set.
914 """
915 return _fields.resolve_default_value(
916 default=self.default,
917 default_factory=self.default_factory,
918 default_factory_takes_validated_data_argument=self.default_factory_takes_validated_data,
919 validated_data=validated_data,
920 call_default_factory=call_default_factory,
921 )
923 def is_required(self) -> bool:
924 """Check if the field is required (i.e., does not have a default value or factory).
926 Returns:
927 `True` if the field is required, `False` otherwise.
928 """
929 return self.default is PydanticUndefined and self.default_factory is None
931 def rebuild_annotation(self) -> Any:
932 """Attempts to rebuild the original annotation for use in function signatures.
934 If metadata is present, it adds it to the original annotation using
935 `Annotated`. Otherwise, it returns the original annotation as-is.
937 Note that because the metadata has been flattened, the original annotation
938 may not be reconstructed exactly as originally provided, e.g. if the original
939 type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
941 Returns:
942 The rebuilt annotation.
943 """
944 if not self.metadata:
945 return self.annotation
946 else:
947 # Annotated arguments must be a tuple
948 return Annotated[(self.annotation, *self.metadata)] # type: ignore
950 def apply_typevars_map(
951 self,
952 typevars_map: Mapping[TypeVar, Any] | None,
953 globalns: GlobalsNamespace | None = None,
954 localns: MappingNamespace | None = None,
955 ) -> None:
956 """Apply a `typevars_map` to the annotation.
958 This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
960 This method applies the `typevars_map` to the annotation in place.
962 Args:
963 typevars_map: A dictionary mapping type variables to their concrete types.
964 globalns: The globals namespace to use during type annotation evaluation.
965 localns: The locals namespace to use during type annotation evaluation.
967 See Also:
968 pydantic._internal._generics.replace_types is used for replacing the typevars with
969 their concrete types.
970 """
971 annotation = _generics.replace_types(self.annotation, typevars_map)
972 annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns)
973 self.annotation = annotation
974 if not evaluated:
975 self._complete = False
976 self._original_annotation = self.annotation
978 def asdict(self) -> _FieldInfoAsDict:
979 """Return a dictionary representation of the `FieldInfo` instance.
981 The returned value is a dictionary with three items:
983 * `annotation`: The type annotation of the field.
984 * `metadata`: The metadata list.
985 * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
986 """
987 return {
988 'annotation': self.annotation,
989 'metadata': self.metadata,
990 'attributes': {attr: getattr(self, attr) for attr in _Attrs},
991 }
993 def _copy(self) -> Self:
994 """Return a copy of the `FieldInfo` instance."""
995 # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
996 # by some third-party libraries with extra attributes defined (and as `FieldInfo`
997 # is slotted, we can't make a copy of the `__dict__`).
998 if type(self) is FieldInfo:
999 # Fast-path if the instance isn't a subclass (`copy.copy()` relies on pickling which is slower):
1000 copied = FieldInfo.__new__(FieldInfo)
1001 for attr_name in FieldInfo.__slots__:
1002 setattr(copied, attr_name, getattr(self, attr_name))
1003 else:
1004 copied = copy(self)
1006 for attr_name in ('metadata', '_attributes_set', '_qualifiers'):
1007 # Apply "deep-copy" behavior on collections attributes:
1008 setattr(copied, attr_name, getattr(copied, attr_name).copy())
1010 return copied # pyright: ignore[reportReturnType]
1012 def __repr_args__(self) -> ReprArgs:
1013 yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation))
1014 yield 'required', self.is_required()
1016 for s in self.__slots__:
1017 # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
1018 # By yielding a three-tuple:
1019 if s in (
1020 'annotation',
1021 '_attributes_set',
1022 '_qualifiers',
1023 '_complete',
1024 '_original_assignment',
1025 '_original_annotation',
1026 '_final',
1027 ):
1028 continue
1029 elif s == 'metadata' and not self.metadata:
1030 continue
1031 elif s == 'repr' and self.repr is True:
1032 continue
1033 if s == 'frozen' and self.frozen is False:
1034 continue
1035 if s == 'validation_alias' and self.validation_alias == self.alias:
1036 continue
1037 if s == 'serialization_alias' and self.serialization_alias == self.alias:
1038 continue
1039 if s == 'default' and self.default is not PydanticUndefined:
1040 yield 'default', self.default
1041 elif s == 'default_factory' and self.default_factory is not None:
1042 yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory))
1043 else:
1044 value = getattr(self, s)
1045 if value is not None and value is not PydanticUndefined:
1046 yield s, value
1049class _EmptyKwargs(TypedDict):
1050 """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`."""
1053_Attrs = {
1054 'default': ...,
1055 'default_factory': None,
1056 'alias': None,
1057 'alias_priority': None,
1058 'validation_alias': None,
1059 'serialization_alias': None,
1060 'title': None,
1061 'field_title_generator': None,
1062 'description': None,
1063 'examples': None,
1064 'exclude': None,
1065 'exclude_if': None,
1066 'discriminator': None,
1067 'deprecated': None,
1068 'json_schema_extra': None,
1069 'frozen': None,
1070 'validate_default': None,
1071 'repr': True,
1072 'init': None,
1073 'init_var': None,
1074 'kw_only': None,
1075}
1077_T = TypeVar('_T')
1080# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
1081# to understand the magic that happens at runtime with the following overloads:
1082@overload # type hint the return value as `Any` to avoid type checking regressions when using `...`.
1083def Field(
1084 default: EllipsisType,
1085 *,
1086 alias: str | None = _Unset,
1087 alias_priority: int | None = _Unset,
1088 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1089 serialization_alias: str | None = _Unset,
1090 title: str | None = _Unset,
1091 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1092 description: str | None = _Unset,
1093 examples: list[Any] | None = _Unset,
1094 exclude: bool | None = _Unset,
1095 exclude_if: Callable[[Any], bool] | None = _Unset,
1096 discriminator: str | types.Discriminator | None = _Unset,
1097 deprecated: Deprecated | str | bool | None = _Unset,
1098 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1099 frozen: bool | None = _Unset,
1100 validate_default: bool | None = _Unset,
1101 repr: bool = _Unset,
1102 init: bool | None = _Unset,
1103 init_var: bool | None = _Unset,
1104 kw_only: bool | None = _Unset,
1105 pattern: str | re.Pattern[str] | None = _Unset,
1106 strict: bool | None = _Unset,
1107 coerce_numbers_to_str: bool | None = _Unset,
1108 gt: annotated_types.SupportsGt | None = _Unset,
1109 ge: annotated_types.SupportsGe | None = _Unset,
1110 lt: annotated_types.SupportsLt | None = _Unset,
1111 le: annotated_types.SupportsLe | None = _Unset,
1112 multiple_of: float | None = _Unset,
1113 allow_inf_nan: bool | None = _Unset,
1114 max_digits: int | None = _Unset,
1115 decimal_places: int | None = _Unset,
1116 min_length: int | None = _Unset,
1117 max_length: int | None = _Unset,
1118 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1119 fail_fast: bool | None = _Unset,
1120 **extra: Unpack[_EmptyKwargs],
1121) -> Any: ...
1122@overload # `default` argument set, validate_default=True (no type checking on the default value)
1123def Field(
1124 default: Any,
1125 *,
1126 alias: str | None = _Unset,
1127 alias_priority: int | None = _Unset,
1128 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1129 serialization_alias: str | None = _Unset,
1130 title: str | None = _Unset,
1131 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1132 description: str | None = _Unset,
1133 examples: list[Any] | None = _Unset,
1134 exclude: bool | None = _Unset,
1135 exclude_if: Callable[[Any], bool] | None = _Unset,
1136 discriminator: str | types.Discriminator | None = _Unset,
1137 deprecated: Deprecated | str | bool | None = _Unset,
1138 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1139 frozen: bool | None = _Unset,
1140 validate_default: Literal[True],
1141 repr: bool = _Unset,
1142 init: bool | None = _Unset,
1143 init_var: bool | None = _Unset,
1144 kw_only: bool | None = _Unset,
1145 pattern: str | re.Pattern[str] | None = _Unset,
1146 strict: bool | None = _Unset,
1147 coerce_numbers_to_str: bool | None = _Unset,
1148 gt: annotated_types.SupportsGt | None = _Unset,
1149 ge: annotated_types.SupportsGe | None = _Unset,
1150 lt: annotated_types.SupportsLt | None = _Unset,
1151 le: annotated_types.SupportsLe | None = _Unset,
1152 multiple_of: float | None = _Unset,
1153 allow_inf_nan: bool | None = _Unset,
1154 max_digits: int | None = _Unset,
1155 decimal_places: int | None = _Unset,
1156 min_length: int | None = _Unset,
1157 max_length: int | None = _Unset,
1158 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1159 fail_fast: bool | None = _Unset,
1160 **extra: Unpack[_EmptyKwargs],
1161) -> Any: ...
1162@overload # `default` argument set, validate_default=False or unset
1163def Field(
1164 default: _T,
1165 *,
1166 alias: str | None = _Unset,
1167 alias_priority: int | None = _Unset,
1168 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1169 serialization_alias: str | None = _Unset,
1170 title: str | None = _Unset,
1171 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1172 description: str | None = _Unset,
1173 examples: list[Any] | None = _Unset,
1174 exclude: bool | None = _Unset,
1175 # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
1176 # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
1177 # `a: int = Field(default_factory=str)` results in a false negative).
1178 exclude_if: Callable[[Any], bool] | None = _Unset,
1179 discriminator: str | types.Discriminator | None = _Unset,
1180 deprecated: Deprecated | str | bool | None = _Unset,
1181 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1182 frozen: bool | None = _Unset,
1183 validate_default: Literal[False] = ...,
1184 repr: bool = _Unset,
1185 init: bool | None = _Unset,
1186 init_var: bool | None = _Unset,
1187 kw_only: bool | None = _Unset,
1188 pattern: str | re.Pattern[str] | None = _Unset,
1189 strict: bool | None = _Unset,
1190 coerce_numbers_to_str: bool | None = _Unset,
1191 gt: annotated_types.SupportsGt | None = _Unset,
1192 ge: annotated_types.SupportsGe | None = _Unset,
1193 lt: annotated_types.SupportsLt | None = _Unset,
1194 le: annotated_types.SupportsLe | None = _Unset,
1195 multiple_of: float | None = _Unset,
1196 allow_inf_nan: bool | None = _Unset,
1197 max_digits: int | None = _Unset,
1198 decimal_places: int | None = _Unset,
1199 min_length: int | None = _Unset,
1200 max_length: int | None = _Unset,
1201 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1202 fail_fast: bool | None = _Unset,
1203 **extra: Unpack[_EmptyKwargs],
1204) -> _T: ...
1205@overload # `default_factory` argument set, validate_default=True (no type checking on the default value)
1206def Field( # pyright: ignore[reportOverlappingOverload]
1207 *,
1208 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
1209 alias: str | None = _Unset,
1210 alias_priority: int | None = _Unset,
1211 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1212 serialization_alias: str | None = _Unset,
1213 title: str | None = _Unset,
1214 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1215 description: str | None = _Unset,
1216 examples: list[Any] | None = _Unset,
1217 exclude: bool | None = _Unset,
1218 exclude_if: Callable[[Any], bool] | None = _Unset,
1219 discriminator: str | types.Discriminator | None = _Unset,
1220 deprecated: Deprecated | str | bool | None = _Unset,
1221 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1222 frozen: bool | None = _Unset,
1223 validate_default: Literal[True],
1224 repr: bool = _Unset,
1225 init: bool | None = _Unset,
1226 init_var: bool | None = _Unset,
1227 kw_only: bool | None = _Unset,
1228 pattern: str | re.Pattern[str] | None = _Unset,
1229 strict: bool | None = _Unset,
1230 coerce_numbers_to_str: bool | None = _Unset,
1231 gt: annotated_types.SupportsGt | None = _Unset,
1232 ge: annotated_types.SupportsGe | None = _Unset,
1233 lt: annotated_types.SupportsLt | None = _Unset,
1234 le: annotated_types.SupportsLe | None = _Unset,
1235 multiple_of: float | None = _Unset,
1236 allow_inf_nan: bool | None = _Unset,
1237 max_digits: int | None = _Unset,
1238 decimal_places: int | None = _Unset,
1239 min_length: int | None = _Unset,
1240 max_length: int | None = _Unset,
1241 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1242 fail_fast: bool | None = _Unset,
1243 **extra: Unpack[_EmptyKwargs],
1244) -> Any: ...
1245@overload # `default_factory` argument set, validate_default=False or unset
1246def Field(
1247 *,
1248 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
1249 alias: str | None = _Unset,
1250 alias_priority: int | None = _Unset,
1251 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1252 serialization_alias: str | None = _Unset,
1253 title: str | None = _Unset,
1254 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1255 description: str | None = _Unset,
1256 examples: list[Any] | None = _Unset,
1257 exclude: bool | None = _Unset,
1258 # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
1259 # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
1260 # `a: int = Field(default_factory=str)` results in a false negative).
1261 exclude_if: Callable[[Any], bool] | None = _Unset,
1262 discriminator: str | types.Discriminator | None = _Unset,
1263 deprecated: Deprecated | str | bool | None = _Unset,
1264 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1265 frozen: bool | None = _Unset,
1266 validate_default: Literal[False] | None = _Unset,
1267 repr: bool = _Unset,
1268 init: bool | None = _Unset,
1269 init_var: bool | None = _Unset,
1270 kw_only: bool | None = _Unset,
1271 pattern: str | re.Pattern[str] | None = _Unset,
1272 strict: bool | None = _Unset,
1273 coerce_numbers_to_str: bool | None = _Unset,
1274 gt: annotated_types.SupportsGt | None = _Unset,
1275 ge: annotated_types.SupportsGe | None = _Unset,
1276 lt: annotated_types.SupportsLt | None = _Unset,
1277 le: annotated_types.SupportsLe | None = _Unset,
1278 multiple_of: float | None = _Unset,
1279 allow_inf_nan: bool | None = _Unset,
1280 max_digits: int | None = _Unset,
1281 decimal_places: int | None = _Unset,
1282 min_length: int | None = _Unset,
1283 max_length: int | None = _Unset,
1284 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1285 fail_fast: bool | None = _Unset,
1286 **extra: Unpack[_EmptyKwargs],
1287) -> _T: ...
1288@overload
1289def Field( # No default set
1290 *,
1291 alias: str | None = _Unset,
1292 alias_priority: int | None = _Unset,
1293 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1294 serialization_alias: str | None = _Unset,
1295 title: str | None = _Unset,
1296 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1297 description: str | None = _Unset,
1298 examples: list[Any] | None = _Unset,
1299 exclude: bool | None = _Unset,
1300 exclude_if: Callable[[Any], bool] | None = _Unset,
1301 discriminator: str | types.Discriminator | None = _Unset,
1302 deprecated: Deprecated | str | bool | None = _Unset,
1303 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1304 frozen: bool | None = _Unset,
1305 validate_default: bool | None = _Unset,
1306 repr: bool = _Unset,
1307 init: bool | None = _Unset,
1308 init_var: bool | None = _Unset,
1309 kw_only: bool | None = _Unset,
1310 pattern: str | re.Pattern[str] | None = _Unset,
1311 strict: bool | None = _Unset,
1312 coerce_numbers_to_str: bool | None = _Unset,
1313 gt: annotated_types.SupportsGt | None = _Unset,
1314 ge: annotated_types.SupportsGe | None = _Unset,
1315 lt: annotated_types.SupportsLt | None = _Unset,
1316 le: annotated_types.SupportsLe | None = _Unset,
1317 multiple_of: float | None = _Unset,
1318 allow_inf_nan: bool | None = _Unset,
1319 max_digits: int | None = _Unset,
1320 decimal_places: int | None = _Unset,
1321 min_length: int | None = _Unset,
1322 max_length: int | None = _Unset,
1323 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1324 fail_fast: bool | None = _Unset,
1325 **extra: Unpack[_EmptyKwargs],
1326) -> Any: ...
1327def Field( # noqa: C901
1328 default: Any = PydanticUndefined,
1329 *,
1330 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
1331 alias: str | None = _Unset,
1332 alias_priority: int | None = _Unset,
1333 validation_alias: str | AliasPath | AliasChoices | None = _Unset,
1334 serialization_alias: str | None = _Unset,
1335 title: str | None = _Unset,
1336 field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
1337 description: str | None = _Unset,
1338 examples: list[Any] | None = _Unset,
1339 exclude: bool | None = _Unset,
1340 exclude_if: Callable[[Any], bool] | None = _Unset,
1341 discriminator: str | types.Discriminator | None = _Unset,
1342 deprecated: Deprecated | str | bool | None = _Unset,
1343 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
1344 frozen: bool | None = _Unset,
1345 validate_default: bool | None = _Unset,
1346 repr: bool = _Unset,
1347 init: bool | None = _Unset,
1348 init_var: bool | None = _Unset,
1349 kw_only: bool | None = _Unset,
1350 pattern: str | re.Pattern[str] | None = _Unset,
1351 strict: bool | None = _Unset,
1352 coerce_numbers_to_str: bool | None = _Unset,
1353 gt: annotated_types.SupportsGt | None = _Unset,
1354 ge: annotated_types.SupportsGe | None = _Unset,
1355 lt: annotated_types.SupportsLt | None = _Unset,
1356 le: annotated_types.SupportsLe | None = _Unset,
1357 multiple_of: float | None = _Unset,
1358 allow_inf_nan: bool | None = _Unset,
1359 max_digits: int | None = _Unset,
1360 decimal_places: int | None = _Unset,
1361 min_length: int | None = _Unset,
1362 max_length: int | None = _Unset,
1363 union_mode: Literal['smart', 'left_to_right'] = _Unset,
1364 fail_fast: bool | None = _Unset,
1365 **extra: Unpack[_EmptyKwargs],
1366) -> Any:
1367 """!!! abstract "Usage Documentation"
1368 [Fields](../concepts/fields.md)
1370 Create a field for objects that can be configured.
1372 Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
1373 apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
1375 Note:
1376 - Any `_Unset` objects will be replaced by the corresponding default value of the `FieldInfo` constructor.
1378 Args:
1379 default: Default value if the field is not set.
1380 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1381 (in which case it is called as is) or a single argument containing the already validated data.
1382 alias: The name to use for the attribute when validating or serializing by alias.
1383 This is often used for things like converting between snake and camel case.
1384 alias_priority: Priority of the alias. This affects whether an alias generator is used.
1385 validation_alias: Like `alias`, but only affects validation, not serialization.
1386 serialization_alias: Like `alias`, but only affects serialization, not validation.
1387 title: Human-readable title.
1388 field_title_generator: A callable that takes a field's name and info and returns title for it.
1389 description: Human-readable description.
1390 examples: Example values for this field.
1391 exclude: Whether to exclude the field from the model serialization.
1392 exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
1393 discriminator: Field name or Discriminator for discriminating the type in a tagged union.
1394 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1395 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1396 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1397 frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
1398 validate_default: If `True`, apply validation to the default value every time you create an instance.
1399 Otherwise, for performance reasons, the default value of the field is trusted and not validated.
1400 repr: A boolean indicating whether to include the field in the `__repr__` output.
1401 init: Whether the field should be included in the constructor of the dataclass.
1402 (Only applies to dataclasses.)
1403 init_var: Whether the field should _only_ be included in the constructor of the dataclass.
1404 (Only applies to dataclasses.)
1405 kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
1406 (Only applies to dataclasses.)
1407 coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
1408 strict: If `True`, strict validation is applied to the field.
1409 See [Strict Mode](../concepts/strict_mode.md) for details.
1410 gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
1411 ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
1412 lt: Less than. If set, value must be less than this. Only applicable to numbers.
1413 le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
1414 multiple_of: Value must be a multiple of this. Only applicable to numbers.
1415 min_length: Minimum length for iterables.
1416 max_length: Maximum length for iterables.
1417 pattern: Pattern for strings (a regular expression).
1418 allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
1419 max_digits: Maximum number of allowed digits for [`Decimal`][decimal.Decimal] numbers.
1420 decimal_places: Maximum number of decimal places allowed for numbers.
1421 union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
1422 See [Union Mode](../concepts/unions.md#union-modes) for details.
1423 fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
1424 This option can be applied only to iterable types (list, tuple, set, and frozenset).
1425 extra: (Deprecated) Extra fields that will be included in the JSON schema.
1427 !!! warning Deprecated
1428 The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
1430 Returns:
1431 A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
1432 type-annotated fields without causing a type error.
1433 """
1434 # Check deprecated and removed params from V1. This logic should eventually be removed.
1435 const = extra.pop('const', None) # type: ignore
1436 if const is not None:
1437 raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs')
1439 min_items = extra.pop('min_items', None) # type: ignore
1440 if min_items is not None:
1441 warn(
1442 '`min_items` is deprecated and will be removed, use `min_length` instead',
1443 PydanticDeprecatedSince20,
1444 stacklevel=2,
1445 )
1446 if min_length in (None, _Unset):
1447 min_length = min_items # type: ignore
1449 max_items = extra.pop('max_items', None) # type: ignore
1450 if max_items is not None:
1451 warn(
1452 '`max_items` is deprecated and will be removed, use `max_length` instead',
1453 PydanticDeprecatedSince20,
1454 stacklevel=2,
1455 )
1456 if max_length in (None, _Unset):
1457 max_length = max_items # type: ignore
1459 unique_items = extra.pop('unique_items', None) # type: ignore
1460 if unique_items is not None:
1461 raise PydanticUserError(
1462 (
1463 '`unique_items` is removed, use `Set` instead'
1464 '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
1465 ),
1466 code='removed-kwargs',
1467 )
1469 allow_mutation = extra.pop('allow_mutation', None) # type: ignore
1470 if allow_mutation is not None:
1471 warn(
1472 '`allow_mutation` is deprecated and will be removed. use `frozen` instead',
1473 PydanticDeprecatedSince20,
1474 stacklevel=2,
1475 )
1476 if allow_mutation is False:
1477 frozen = True
1479 regex = extra.pop('regex', None) # type: ignore
1480 if regex is not None:
1481 raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs')
1483 if extra:
1484 warn(
1485 'Using extra keyword arguments on `Field` is deprecated and will be removed.'
1486 ' Use `json_schema_extra` instead.'
1487 f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
1488 PydanticDeprecatedSince20,
1489 stacklevel=2,
1490 )
1491 if not json_schema_extra or json_schema_extra is _Unset:
1492 json_schema_extra = extra # type: ignore
1494 if (
1495 validation_alias
1496 and validation_alias is not _Unset
1497 and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
1498 ):
1499 raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')
1501 if serialization_alias in (_Unset, None) and isinstance(alias, str):
1502 serialization_alias = alias
1504 if validation_alias in (_Unset, None):
1505 validation_alias = alias
1507 include = extra.pop('include', None) # type: ignore
1508 if include is not None:
1509 warn(
1510 '`include` is deprecated and does nothing. It will be removed, use `exclude` instead',
1511 PydanticDeprecatedSince20,
1512 stacklevel=2,
1513 )
1515 return FieldInfo.from_field(
1516 default,
1517 default_factory=default_factory,
1518 alias=alias,
1519 alias_priority=alias_priority,
1520 validation_alias=validation_alias,
1521 serialization_alias=serialization_alias,
1522 title=title,
1523 field_title_generator=field_title_generator,
1524 description=description,
1525 examples=examples,
1526 exclude=exclude,
1527 exclude_if=exclude_if,
1528 discriminator=discriminator,
1529 deprecated=deprecated,
1530 json_schema_extra=json_schema_extra,
1531 frozen=frozen,
1532 pattern=pattern,
1533 validate_default=validate_default,
1534 repr=repr,
1535 init=init,
1536 init_var=init_var,
1537 kw_only=kw_only,
1538 coerce_numbers_to_str=coerce_numbers_to_str,
1539 strict=strict,
1540 gt=gt,
1541 ge=ge,
1542 lt=lt,
1543 le=le,
1544 multiple_of=multiple_of,
1545 min_length=min_length,
1546 max_length=max_length,
1547 allow_inf_nan=allow_inf_nan,
1548 max_digits=max_digits,
1549 decimal_places=decimal_places,
1550 union_mode=union_mode,
1551 fail_fast=fail_fast,
1552 )
1555_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters)
1556_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter
1559class ModelPrivateAttr(_repr.Representation):
1560 """A descriptor for private attributes in class models.
1562 !!! warning
1563 You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
1564 the [`PrivateAttr()`][pydantic.fields.PrivateAttr] function.
1566 Attributes:
1567 default: The default value of the attribute if not provided.
1568 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1569 (in which case it is called as is) or a single argument containing the validated data (the model's
1570 [`__dict__`][object.__dict__]) and the already initialized private attributes.
1571 """
1573 __slots__ = ('default', 'default_factory', '_default_factory_takes_validated_data')
1575 def __init__(
1576 self,
1577 default: Any = PydanticUndefined,
1578 *,
1579 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
1580 ) -> None:
1581 if default is Ellipsis:
1582 self.default = PydanticUndefined
1583 else:
1584 self.default = default
1585 self.default_factory = default_factory
1586 self._default_factory_takes_validated_data: bool | None = _Unset
1588 if not TYPE_CHECKING:
1589 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
1591 def __getattr__(self, item: str) -> Any:
1592 """This function improves compatibility with custom descriptors by ensuring delegation happens
1593 as expected when the default value of a private attribute is a descriptor.
1594 """
1595 if item in {'__get__', '__set__', '__delete__'}:
1596 if hasattr(self.default, item):
1597 return getattr(self.default, item)
1598 raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
1600 def __set_name__(self, cls: type[Any], name: str) -> None:
1601 """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
1602 default = self.default
1603 if default is PydanticUndefined:
1604 return
1605 set_name = getattr(default, '__set_name__', None)
1606 if callable(set_name):
1607 set_name(cls, name)
1609 @property
1610 def default_factory_takes_validated_data(self) -> bool | None:
1611 """Whether the provided default factory callable has a validated data parameter.
1613 Returns `None` if no default factory is set.
1614 """
1615 if self._default_factory_takes_validated_data is not _Unset:
1616 return self._default_factory_takes_validated_data
1618 value: bool | None = None
1619 if self.default_factory is not None:
1620 value = _fields.takes_validated_data_argument(self.default_factory)
1622 self._default_factory_takes_validated_data = value
1623 return value
1625 @overload
1626 def get_default(
1627 self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
1628 ) -> Any: ...
1630 @overload
1631 def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
1633 def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
1634 """Get the default value.
1636 We expose an option for whether to call the default_factory (if present), as calling it may
1637 result in side effects that we want to avoid. However, there are times when it really should
1638 be called (namely, when instantiating a model via `model_construct`).
1640 Args:
1641 call_default_factory: Whether to call the default factory or not.
1642 validated_data: The already validated data to be passed to the default factory.
1644 Returns:
1645 The default value, calling the default factory if requested or `None` if not set.
1646 """
1647 return _fields.resolve_default_value(
1648 default=self.default,
1649 default_factory=self.default_factory,
1650 default_factory_takes_validated_data_argument=self.default_factory_takes_validated_data,
1651 validated_data=validated_data,
1652 call_default_factory=call_default_factory,
1653 )
1655 def __eq__(self, other: Any) -> bool:
1656 return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
1657 other.default,
1658 other.default_factory,
1659 )
1661 def __repr_args__(self) -> ReprArgs:
1662 if self.default is not PydanticUndefined:
1663 yield 'default', self.default
1664 if self.default_factory is not None:
1665 yield 'default_factory', self.default_factory
1668# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
1669# to understand the magic that happens at runtime.
1670@overload # `default` argument set
1671def PrivateAttr(
1672 default: _T,
1673 *,
1674 init: Literal[False] = False,
1675) -> _T: ...
1676@overload # `default_factory` argument set
1677def PrivateAttr(
1678 *,
1679 default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
1680 init: Literal[False] = False,
1681) -> _T: ...
1682@overload # No default set
1683def PrivateAttr(
1684 *,
1685 init: Literal[False] = False,
1686) -> Any: ...
1687def PrivateAttr(
1688 default: Any = PydanticUndefined,
1689 *,
1690 default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = None,
1691 init: Literal[False] = False,
1692) -> Any:
1693 """!!! abstract "Usage Documentation"
1694 [Private Model Attributes](../concepts/models.md#private-model-attributes)
1696 Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
1698 Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
1700 Private attributes are stored in `__private_attributes__` on the model.
1702 Args:
1703 default: The attribute's default value. Defaults to Undefined.
1704 default_factory: A callable to generate the default value. The callable can either take 0 arguments
1705 (in which case it is called as is) or a single argument containing the validated data (the model's
1706 [`__dict__`][object.__dict__]) and the already initialized private attributes.
1707 If both `default` and `default_factory` are set, an error will be raised.
1708 init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
1710 Returns:
1711 An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
1713 Raises:
1714 TypeError: If both `default` and `default_factory` are set.
1715 """
1716 if default is not PydanticUndefined and default_factory is not None:
1717 raise TypeError('cannot specify both default and default_factory')
1719 return ModelPrivateAttr(
1720 default,
1721 default_factory=default_factory,
1722 )
1725@dataclasses.dataclass(slots=True)
1726class ComputedFieldInfo:
1727 """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
1729 Attributes:
1730 decorator_repr: A class variable representing the decorator string, '@computed_field'.
1731 wrapped_property: The wrapped computed field property.
1732 return_type: The type of the computed field property's return value.
1733 alias: The alias of the property to be used during serialization.
1734 alias_priority: The priority of the alias. This affects whether an alias generator is used.
1735 title: Title of the computed field to include in the serialization JSON schema.
1736 field_title_generator: A callable that takes a field's name and info and returns title for it.
1737 description: Description of the computed field to include in the serialization JSON schema.
1738 deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
1739 or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
1740 examples: Example values of the computed field to include in the serialization JSON schema.
1741 json_schema_extra: A dict or callable to provide extra JSON schema properties.
1742 repr: A boolean indicating whether to include the field in the __repr__ output.
1743 """
1745 decorator_repr: ClassVar[str] = '@computed_field'
1746 wrapped_property: property
1747 return_type: Any
1748 alias: str | None
1749 alias_priority: int | None
1750 exclude_if: Callable[[Any], bool] | None
1751 title: str | None
1752 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None
1753 description: str | None
1754 deprecated: Deprecated | str | bool | None
1755 examples: list[Any] | None
1756 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
1757 repr: bool
1758 # NOTE: if you add a new field, add it to the `__copy__()` implementation.
1760 def __copy__(self) -> Self:
1761 return type(self)(
1762 wrapped_property=self.wrapped_property,
1763 return_type=self.return_type,
1764 alias=self.alias,
1765 alias_priority=self.alias_priority,
1766 exclude_if=self.exclude_if,
1767 title=self.title,
1768 field_title_generator=self.field_title_generator,
1769 description=self.description,
1770 deprecated=self.deprecated,
1771 examples=self.examples.copy() if isinstance(self.examples, list) else self.examples,
1772 json_schema_extra=self.json_schema_extra.copy()
1773 if isinstance(self.json_schema_extra, dict)
1774 else self.json_schema_extra,
1775 repr=self.repr,
1776 )
1778 @property
1779 def deprecation_message(self) -> str | None:
1780 """The deprecation message to be emitted, or `None` if not set."""
1781 if self.deprecated is None:
1782 return None
1783 if isinstance(self.deprecated, bool):
1784 return 'deprecated' if self.deprecated else None
1785 return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
1787 def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None:
1788 """Update the instance from the configuration set on the class this computed field belongs to."""
1789 title_generator = self.field_title_generator or config_wrapper.field_title_generator
1790 if title_generator is not None and self.title is None:
1791 self.title = title_generator(name, self)
1792 if config_wrapper.alias_generator is not None:
1793 self._apply_alias_generator(config_wrapper.alias_generator, name)
1795 def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None:
1796 """Apply an alias generator to aliases if appropriate.
1798 Args:
1799 alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
1800 name: The name of the computed field from which to generate the alias.
1801 """
1802 # Apply an alias_generator if
1803 # 1. An alias is not specified
1804 # 2. An alias is specified, but the priority is <= 1
1806 if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None:
1807 alias, _, serialization_alias = None, None, None
1809 if isinstance(alias_generator, AliasGenerator):
1810 alias, _, serialization_alias = alias_generator.generate_aliases(name)
1811 elif callable(alias_generator):
1812 alias = alias_generator(name)
1814 # if priority is not set, we set to 1
1815 # which supports the case where the alias_generator from a child class is used
1816 # to generate an alias for a field in a parent class
1817 if self.alias_priority is None or self.alias_priority <= 1:
1818 self.alias_priority = 1
1820 # if the priority is 1, then we set the aliases to the generated alias
1821 # note that we use the serialization_alias with priority over alias, as computed_field
1822 # aliases are used for serialization only (not validation)
1823 if self.alias_priority == 1:
1824 self.alias = _utils.get_first_not_none(serialization_alias, alias)
1827def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore
1828 """Returns true if provided property is private, False otherwise."""
1829 wrapped_name: str = ''
1831 if isinstance(property_, property):
1832 wrapped_name = getattr(property_.fget, '__name__', '')
1833 elif isinstance(property_, cached_property): # type: ignore
1834 wrapped_name = getattr(property_.func, '__name__', '') # type: ignore
1836 return wrapped_name.startswith('_') and not wrapped_name.startswith('__')
1839# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
1840# See https://github.com/python/typing/issues/985 and linked issues
1841PropertyT = TypeVar('PropertyT')
1844@overload
1845def computed_field(func: PropertyT, /) -> PropertyT: ...
1848@overload
1849def computed_field(
1850 *,
1851 alias: str | None = None,
1852 alias_priority: int | None = None,
1853 exclude_if: Callable[[Any], bool] | None = None,
1854 title: str | None = None,
1855 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
1856 description: str | None = None,
1857 deprecated: Deprecated | str | bool | None = None,
1858 examples: list[Any] | None = None,
1859 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
1860 repr: bool = True,
1861 return_type: Any = PydanticUndefined,
1862) -> Callable[[PropertyT], PropertyT]: ...
1865def computed_field(
1866 func: PropertyT | None = None,
1867 /,
1868 *,
1869 alias: str | None = None,
1870 alias_priority: int | None = None,
1871 exclude_if: Callable[[Any], bool] | None = None,
1872 title: str | None = None,
1873 field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
1874 description: str | None = None,
1875 deprecated: Deprecated | str | bool | None = None,
1876 examples: list[Any] | None = None,
1877 json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
1878 repr: bool | None = None,
1879 return_type: Any = PydanticUndefined,
1880) -> PropertyT | Callable[[PropertyT], PropertyT]:
1881 """!!! abstract "Usage Documentation"
1882 [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
1884 Decorator to include `property` and `cached_property` when serializing models or dataclasses.
1886 This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
1888 ```python
1889 from pydantic import BaseModel, computed_field
1891 class Rectangle(BaseModel):
1892 width: int
1893 length: int
1895 @computed_field
1896 @property
1897 def area(self) -> int:
1898 return self.width * self.length
1900 print(Rectangle(width=3, length=2).model_dump())
1901 #> {'width': 3, 'length': 2, 'area': 6}
1902 ```
1904 If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
1905 automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
1906 and confuse static type checkers, thus explicit use of `@property` is recommended.
1908 !!! warning "Mypy Warning"
1909 Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
1910 mypy may throw a `Decorated property not supported` error.
1911 See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
1912 To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
1914 [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
1916 ```python
1917 import random
1919 from pydantic import BaseModel, computed_field
1921 class Square(BaseModel):
1922 width: float
1924 @computed_field
1925 def area(self) -> float: # converted to a `property` by `computed_field`
1926 return round(self.width**2, 2)
1928 @area.setter
1929 def area(self, new_area: float) -> None:
1930 self.width = new_area**0.5
1932 @computed_field(alias='the magic number', repr=False)
1933 def random_number(self) -> int:
1934 return random.randint(0, 1_000)
1936 square = Square(width=1.3)
1938 # `random_number` does not appear in representation
1939 print(repr(square))
1940 #> Square(width=1.3, area=1.69)
1942 print(square.random_number)
1943 #> 3
1945 square.area = 4
1947 print(square.model_dump_json(by_alias=True))
1948 #> {"width":2.0,"area":4.0,"the magic number":3}
1949 ```
1951 !!! warning "Overriding with `computed_field`"
1952 You can't override a field from a parent class with a `computed_field` in the child class.
1953 `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
1954 See the example below:
1956 ```python
1957 from pydantic import BaseModel, computed_field
1959 class Parent(BaseModel):
1960 a: str
1962 try:
1964 class Child(Parent):
1965 @computed_field
1966 @property
1967 def a(self) -> str:
1968 return 'new a'
1970 except TypeError as e:
1971 print(e)
1972 '''
1973 Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
1974 '''
1975 ```
1977 Private properties decorated with `@computed_field` have `repr=False` by default.
1979 ```python
1980 from functools import cached_property
1982 from pydantic import BaseModel, computed_field
1984 class Model(BaseModel):
1985 foo: int
1987 @computed_field
1988 @cached_property
1989 def _private_cached_property(self) -> int:
1990 return -self.foo
1992 @computed_field
1993 @property
1994 def _private_property(self) -> int:
1995 return -self.foo
1997 m = Model(foo=1)
1998 print(repr(m))
1999 #> Model(foo=1)
2000 ```
2002 Args:
2003 func: the function to wrap.
2004 alias: alias to use when serializing this computed field, only used when `by_alias=True`
2005 alias_priority: priority of the alias. This affects whether an alias generator is used
2006 exclude_if: A callable that determines whether to exclude this computed field during serialization based on its value.
2007 title: Title to use when including this computed field in JSON Schema
2008 field_title_generator: A callable that takes a field's name and info and returns title for it.
2009 description: Description to use when including this computed field in JSON Schema, defaults to the function's
2010 docstring
2011 deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
2012 to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
2013 `deprecated` decorator.
2014 examples: Example values to use when including this computed field in JSON Schema
2015 json_schema_extra: A dict or callable to provide extra JSON schema properties.
2016 repr: whether to include this computed field in model repr.
2017 Default is `False` for private properties and `True` for public properties.
2018 return_type: optional return for serialization logic to expect when serializing to JSON, if included
2019 this must be correct, otherwise a `TypeError` is raised.
2020 If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
2021 objects.
2023 Returns:
2024 A proxy wrapper for the property.
2025 """
2027 def dec(f: Any) -> Any:
2028 nonlocal description, deprecated, return_type, alias_priority
2029 unwrapped = _decorators.unwrap_wrapped_function(f)
2031 if description is None and unwrapped.__doc__:
2032 description = inspect.cleandoc(unwrapped.__doc__)
2034 if deprecated is None and hasattr(unwrapped, '__deprecated__'):
2035 deprecated = unwrapped.__deprecated__
2037 # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
2038 f = _decorators.ensure_property(f)
2039 alias_priority = (alias_priority or 2) if alias is not None else None
2041 if repr is None:
2042 repr_: bool = not _wrapped_property_is_private(property_=f)
2043 else:
2044 repr_ = repr
2046 dec_info = ComputedFieldInfo(
2047 f,
2048 return_type,
2049 alias,
2050 alias_priority,
2051 exclude_if,
2052 title,
2053 field_title_generator,
2054 description,
2055 deprecated,
2056 examples,
2057 json_schema_extra,
2058 repr_,
2059 )
2060 return _decorators.PydanticDescriptorProxy(f, dec_info)
2062 if func is None:
2063 return dec
2064 else:
2065 return dec(func)