Fields
Defining fields on models.
Bases: Representation
This class holds information about a field.
FieldInfo is used for any field definition regardless of whether the Field()
function is explicitly used.
Type: type[Any] | None
Type: Any
Type: typing.Callable[[], Any] | None Default: kwargs.pop('default_factory', None)
Type: str | None Default: kwargs.pop('alias', None)
Type: int | None Default: kwargs.pop('alias_priority', None) or 2 if alias_is_set else None
Type: str | AliasPath | AliasChoices | None Default: kwargs.pop('validation_alias', None)
Type: str | None Default: kwargs.pop('serialization_alias', None)
Type: str | None Default: kwargs.pop('title', None)
Type: str | None Default: kwargs.pop('description', None)
Type: list[Any] | None Default: kwargs.pop('examples', None)
Type: bool | None Default: kwargs.pop('exclude', None)
Type: str | types.Discriminator | None Default: kwargs.pop('discriminator', None)
Type: Deprecated | str | bool | None Default: kwargs.pop('deprecated', getattr(self, 'deprecated', None))
Type: JsonDict | typing.Callable[[JsonDict], None] | None Default: kwargs.pop('json_schema_extra', None)
Type: bool | None Default: kwargs.pop('frozen', None)
Type: bool | None Default: kwargs.pop('validate_default', None)
Type: bool Default: kwargs.pop('repr', True)
Type: bool | None Default: kwargs.pop('init', None)
Type: bool | None Default: kwargs.pop('init_var', None)
Type: bool | None Default: kwargs.pop('kw_only', None)
Type: list[Any] Default: self._collect_metadata(kwargs) + annotation_metadata
Type: dict[str, typing.Callable[[Any], Any] | None] Default: \{'strict': types.Strict, 'gt': annotated_types.Gt, 'ge': annotated_types.Ge, 'lt': annotated_types.Lt, 'le': annotated_types.Le, 'multiple_of': annotated_types.MultipleOf, 'min_length': annotated_types.MinLen, 'max_length': annotated_types.MaxLen, 'pattern': None, 'allow_inf_nan': None, 'max_digits': None, 'decimal_places': None, 'union_mode': None, 'coerce_numbers_to_str': None\}
The deprecation message to be emitted, or None if not set.
Type: str | None
def __init__(kwargs: Unpack[_FieldInfoInputs] = {}) -> None
This class should generally not be initialized directly; instead, use the pydantic.fields.Field function
or one of the constructor classmethods.
See the signature of pydantic.fields.Field for more details about the expected arguments.
None
@staticmethod
def from_field(
default: Any = PydanticUndefined,
kwargs: Unpack[_FromFieldInfoInputs] = {},
) -> FieldInfo
Create a new FieldInfo object with the Field function.
FieldInfo — A new FieldInfo object with the given parameters.
The default value for the field. Defaults to Undefined.
Additional arguments dictionary.
TypeError— If ‘annotation’ is passed as a keyword argument.
@staticmethod
def from_annotation(annotation: type[Any]) -> FieldInfo
Creates a FieldInfo instance from a bare annotation.
This function is used internally to create a FieldInfo from a bare annotation like this:
import pydantic
class MyModel(pydantic.BaseModel):
foo: int # <-- like this
We also account for the case where the annotation can be an instance of Annotated and where
one of the (not first) arguments in Annotated is an instance of FieldInfo, e.g.:
import annotated_types
from typing_extensions import Annotated
import pydantic
class MyModel(pydantic.BaseModel):
foo: Annotated[int, annotated_types.Gt(42)]
bar: Annotated[int, pydantic.Field(gt=42)]
FieldInfo — An instance of the field metadata.
An annotation object.
@staticmethod
def from_annotated_attribute(annotation: type[Any], default: Any) -> FieldInfo
Create FieldInfo from an annotation with a default value.
This is used in cases like the following:
import annotated_types
from typing_extensions import Annotated
import pydantic
class MyModel(pydantic.BaseModel):
foo: int = 4 # <-- like this
bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
FieldInfo — A field object with the passed values.
The type annotation of the field.
The default value of the field.
@staticmethod
def merge_field_infos(field_infos: FieldInfo = (), overrides: Any = {}) -> FieldInfo
Merge FieldInfo instances keeping only explicitly set attributes.
Later FieldInfo instances override earlier ones.
FieldInfo — A merged FieldInfo instance.
def get_default(call_default_factory: bool = False) -> Any
Get the default value.
We expose an option for whether to call the default_factory (if present), as calling it may
result in side effects that we want to avoid. However, there are times when it really should
be called (namely, when instantiating a model via model_construct).
Any — The default value, calling the default factory if requested or None if not set.
Whether to call the default_factory or not. Defaults to False.
def is_required() -> bool
Check if the field is required (i.e., does not have a default value or factory).
bool — True if the field is required, False otherwise.
def rebuild_annotation() -> Any
Attempts to rebuild the original annotation for use in function signatures.
If metadata is present, it adds it to the original annotation using
Annotated. Otherwise, it returns the original annotation as-is.
Note that because the metadata has been flattened, the original annotation
may not be reconstructed exactly as originally provided, e.g. if the original
type had unrecognized annotations, or was annotated with a call to pydantic.Field.
Any — The rebuilt annotation.
def apply_typevars_map(
typevars_map: dict[Any, Any] | None,
types_namespace: dict[str, Any] | None,
) -> None
Apply a typevars_map to the annotation.
This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
This method applies the typevars_map to the annotation in place.
None
A dictionary mapping type variables to their concrete types.
A dictionary containing related types to the annotated type.
Bases: Representation
A descriptor for private attributes in class models.
Default: default
Default: default_factory
def __getattr__(item: str) -> Any
This function improves compatibility with custom descriptors by ensuring delegation happens as expected when the default value of a private attribute is a descriptor.
Any
def __set_name__(cls: type[Any], name: str) -> None
Preserve __set_name__ protocol defined in https://peps.python.org/pep-0487.
None
def get_default() -> Any
Retrieve the default value of the object.
If self.default_factory is None, the method will return a deep copy of the self.default object.
If self.default_factory is not None, it will call self.default_factory and return the value returned.
Any — The default value of the object.
A container for data from @computed_field so that we can access it while building the pydantic-core schema.
Type: str Default: '@computed_field'
Type: property
Type: Any
Type: str | None
Type: int | None
Type: str | None
Type: str | None
Type: Deprecated | str | bool | None
Type: list[Any] | None
Type: JsonDict | typing.Callable[[JsonDict], None] | None
Type: bool
The deprecation message to be emitted, or None if not set.
Type: str | None
def Field(
default: Any = PydanticUndefined,
default_factory: typing.Callable[[], Any] | None = _Unset,
alias: str | None = _Unset,
alias_priority: int | None = _Unset,
validation_alias: str | AliasPath | AliasChoices | None = _Unset,
serialization_alias: str | None = _Unset,
title: str | None = _Unset,
description: str | None = _Unset,
examples: list[Any] | None = _Unset,
exclude: bool | None = _Unset,
discriminator: str | types.Discriminator | None = _Unset,
deprecated: Deprecated | str | bool | None = _Unset,
json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = _Unset,
frozen: bool | None = _Unset,
validate_default: bool | None = _Unset,
repr: bool = _Unset,
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | typing.Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
coerce_numbers_to_str: bool | None = _Unset,
gt: float | None = _Unset,
ge: float | None = _Unset,
lt: float | None = _Unset,
le: float | None = _Unset,
multiple_of: float | None = _Unset,
allow_inf_nan: bool | None = _Unset,
max_digits: int | None = _Unset,
decimal_places: int | None = _Unset,
min_length: int | None = _Unset,
max_length: int | None = _Unset,
union_mode: Literal['smart', 'left_to_right'] = _Unset,
extra: Unpack[_EmptyKwargs] = {},
) -> Any
Usage docs: https://docs.pydantic.dev/2.7/concepts/fields
Create a field for objects that can be configured.
Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
apply only to number fields (int, float, Decimal) and some apply only to str.
Any — A new FieldInfo. The return annotation is Any so Field can be used on
type-annotated fields without causing a type error.
Default value if the field is not set.
A callable to generate the default value, such as :func:~datetime.utcnow.
The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case.
Priority of the alias. This affects whether an alias generator is used.
Like alias, but only affects validation, not serialization.
Like alias, but only affects serialization, not validation.
Human-readable title.
Human-readable description.
Example values for this field.
Whether to exclude the field from the model serialization.
Field name or Discriminator for discriminating the type in a tagged union.
A deprecation message, an instance of warnings.deprecated or the typing_extensions.deprecated backport,
or a boolean. If True, a default deprecation message will be emitted when accessing the field.
A dict or callable to provide extra JSON schema properties.
Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
If True, apply validation to the default value every time you create an instance.
Otherwise, for performance reasons, the default value of the field is trusted and not validated.
A boolean indicating whether to include the field in the __repr__ output.
Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)
Whether the field should only be included in the constructor of the dataclass. (Only applies to dataclasses.)
Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)
Whether to enable coercion of any Number type to str (not applicable in strict mode).
If True, strict validation is applied to the field.
See Strict Mode for details.
Greater than. If set, value must be greater than this. Only applicable to numbers.
Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
Less than. If set, value must be less than this. Only applicable to numbers.
Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
Value must be a multiple of this. Only applicable to numbers.
Minimum length for iterables.
Maximum length for iterables.
Pattern for strings (a regular expression).
Allow inf, -inf, nan. Only applicable to numbers.
Maximum number of allow digits for strings.
Maximum number of decimal places allowed for numbers.
The strategy to apply when validating a union. Can be smart (the default), or left_to_right.
See Union Mode for details.
(Deprecated) Extra fields that will be included in the JSON schema.
def PrivateAttr(
default: Any = PydanticUndefined,
default_factory: typing.Callable[[], Any] | None = None,
) -> Any
Usage docs: https://docs.pydantic.dev/2.7/concepts/models/#private-model-attributes
Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
Private attributes are not validated by Pydantic, so it’s up to you to ensure they are used in a type-safe manner.
Private attributes are stored in __private_attributes__ on the model.
Any — An instance of ModelPrivateAttr class.
The attribute’s default value. Defaults to Undefined.
Callable that will be
called when a default value is needed for this attribute.
If both default and default_factory are set, an error will be raised.
ValueError— If bothdefaultanddefault_factoryare set.
def computed_field(
alias: str | None = None,
alias_priority: int | None = None,
title: str | None = None,
description: str | None = None,
deprecated: Deprecated | str | bool | None = None,
examples: list[Any] | None = None,
json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None,
repr: bool = True,
return_type: Any = PydanticUndefined,
) -> typing.Callable[[PropertyT], PropertyT]
def computed_field(__func: PropertyT) -> PropertyT
Usage docs: https://docs.pydantic.dev/2.7/concepts/fields#the-computed_field-decorator
Decorator to include property and cached_property when serializing models or dataclasses.
This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
from pydantic import BaseModel, computed_field
class Rectangle(BaseModel):
width: int
length: int
@computed_field
@property
def area(self) -> int:
return self.width * self.length
print(Rectangle(width=3, length=2).model_dump())
#> {'width': 3, 'length': 2, 'area': 6}
If applied to functions not yet decorated with @property or @cached_property, the function is
automatically wrapped with property. Although this is more concise, you will lose IntelliSense in your IDE,
and confuse static type checkers, thus explicit use of @property is recommended.
import random
from pydantic import BaseModel, computed_field
class Square(BaseModel):
width: float
@computed_field
def area(self) -> float: # converted to a `property` by `computed_field`
return round(self.width**2, 2)
@area.setter
def area(self, new_area: float) -> None:
self.width = new_area**0.5
@computed_field(alias='the magic number', repr=False)
def random_number(self) -> int:
return random.randint(0, 1_000)
square = Square(width=1.3)
# `random_number` does not appear in representation
print(repr(square))
#> Square(width=1.3, area=1.69)
print(square.random_number)
#> 3
square.area = 4
print(square.model_dump_json(by_alias=True))
#> {"width":2.0,"area":4.0,"the magic number":3}
from pydantic import BaseModel, computed_field
class Parent(BaseModel):
a: str
try:
class Child(Parent):
@computed_field
@property
def a(self) -> str:
return 'new a'
except ValueError as e:
print(repr(e))
#> ValueError("you can't override a field with a computed field")
Private properties decorated with @computed_field have repr=False by default.
from functools import cached_property
from pydantic import BaseModel, computed_field
class Model(BaseModel):
foo: int
@computed_field
@cached_property
def _private_cached_property(self) -> int:
return -self.foo
@computed_field
@property
def _private_property(self) -> int:
return -self.foo
m = Model(foo=1)
print(repr(m))
#> M(foo=1)
PropertyT | typing.Callable[[PropertyT], PropertyT] — A proxy wrapper for the property.
the function to wrap.
alias to use when serializing this computed field, only used when by_alias=True
priority of the alias. This affects whether an alias generator is used
Title to use when including this computed field in JSON Schema
Description to use when including this computed field in JSON Schema, defaults to the function’s docstring
A deprecation message (or an instance of warnings.deprecated or the typing_extensions.deprecated backport).
to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
deprecated decorator.
Example values to use when including this computed field in JSON Schema
A dict or callable to provide extra JSON schema properties.
whether to include this computed field in model repr.
Default is False for private properties and True for public properties.
optional return for serialization logic to expect when serializing to JSON, if included
this must be correct, otherwise a TypeError is raised.
If you don’t include a return type Any is used, which does runtime introspection to handle arbitrary
objects.
Type: TypeAlias Default: Dict[str, JsonValue]
Type: typing_extensions.TypeAlias Default: 'typing.Iterable[tuple[str | None, Any]]'
Default: PydanticDeprecatedSince20
Type: TypeAlias Default: warnings.deprecated | deprecated
Default: typing.TypeVar('PropertyT')