Skip to content
You're viewing docs for v2.0. See the latest version →

pydantic.fields

Defining fields on models.

PydanticUserError

Bases: PydanticErrorMixin, TypeError

An error raised due to incorrect use of Pydantic.


PydanticDeprecatedSince20

Bases: PydanticDeprecationWarning

A specific PydanticDeprecationWarning subclass defining functionality deprecated since Pydantic 2.0.


FieldInfo

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.

Attributes

annotation

Type: type[Any] | None

default

Type: Any

default_factory

Type: typing.Callable[[], Any] | None Default: kwargs.pop('default_factory', None)

alias

Type: str | None Default: kwargs.pop('alias', None)

alias_priority

Type: int | None Default: kwargs.pop('alias_priority', None) or 2 if alias_is_set else None

validation_alias

Type: str | AliasPath | AliasChoices | None Default: kwargs.pop('validation_alias', None)

serialization_alias

Type: str | None Default: kwargs.pop('serialization_alias', None)

title

Type: str | None Default: kwargs.pop('title', None)

description

Type: str | None Default: kwargs.pop('description', None)

examples

Type: list[Any] | None Default: kwargs.pop('examples', None)

exclude

Type: bool | None Default: kwargs.pop('exclude', None)

include

Type: bool | None Default: kwargs.pop('include', None)

discriminator

Type: str | None Default: kwargs.pop('discriminator', None)

json_schema_extra

Type: dict[str, Any] | None Default: kwargs.pop('json_schema_extra', None)

frozen

Type: bool | None Default: kwargs.pop('frozen', None)

validate_default

Type: bool | None Default: kwargs.pop('validate_default', None)

repr

Type: bool Default: kwargs.pop('repr', True)

init_var

Type: bool | None Default: kwargs.pop('init_var', None)

kw_only

Type: bool | None Default: kwargs.pop('kw_only', None)

metadata

Type: list[Any] Default: self._collect_metadata(kwargs) + annotation_metadata

metadata_lookup

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\}

Methods

init

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.

Returns

None

from_field

@classmethod

def from_field(
    cls,
    default: Any = PydanticUndefined,
    kwargs: Unpack[_FromFieldInfoInputs] = {},
) -> typing_extensions.Self

Create a new FieldInfo object with the Field function.

Returns

typing_extensions.Self — A new FieldInfo object with the given parameters.

Parameters

default : Any Default: PydanticUndefined

The default value for the field. Defaults to Undefined.

**kwargs : Unpack[_FromFieldInfoInputs] Default: \{\}

Additional arguments dictionary.

Raises
  • TypeError — If ‘annotation’ is passed as a keyword argument.

from_annotation

@classmethod

def from_annotation(cls, annotation: type[Any]) -> typing_extensions.Self

Creates a FieldInfo instance from a bare annotation.

Returns

typing_extensions.Self — An instance of the field metadata.

Parameters

annotation : type[Any]

An annotation object.

from_annotated_attribute

@classmethod

def from_annotated_attribute(
    cls,
    annotation: type[Any],
    default: Any,
) -> typing_extensions.Self

Create FieldInfo from an annotation with a default value.

Returns

typing_extensions.Self — A field object with the passed values.

Parameters

annotation : type[Any]

The type annotation of the field.

default : Any

The default value of the field.

merge_field_infos

@staticmethod

def merge_field_infos(field_infos: FieldInfo = (), overrides: Any = {}) -> FieldInfo

Merge FieldInfo instances keeping only explicitly set attributes.

Returns

FieldInfo — A merged FieldInfo instance.

get_default

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).

Returns

Any — The default value, calling the default factory if requested or None if not set.

Parameters

call_default_factory : bool Default: False

Whether to call the default_factory or not. Defaults to False.

is_required

def is_required() -> bool

Check if the argument is required.

Returns

boolTrue if the argument is required, False otherwise.

rebuild_annotation

def rebuild_annotation() -> Any

Rebuilds the original annotation for use in function signatures.

If metadata is present, it adds it to the original annotation using an AnnotatedAlias. Otherwise, it returns the original annotation as is.

Returns

Any — The rebuilt annotation.

apply_typevars_map

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.

Returns

None

Parameters

typevars_map : dict[Any, Any] | None

A dictionary mapping type variables to their concrete types.

types_namespace : dict | None

A dictionary containing related types to the annotated type.


AliasPath

usage docs: https://docs.pydantic.dev/dev-v2/usage/fields#aliaspath-and-aliaschoices

A data class used by validation_alias as a convenience to create aliases.

Attributes

path

Type: list[int | str] Default: [first_arg] + list(args)

Methods

convert_to_aliases

def convert_to_aliases() -> list[str | int]

Converts arguments to a list of string or integer aliases.

Returns

list[str | int] — The list of aliases.


AliasChoices

usage docs: https://docs.pydantic.dev/dev-v2/usage/fields#aliaspath-and-aliaschoices

A data class used by validation_alias as a convenience to create aliases.

Attributes

choices

Type: list[str | AliasPath] Default: [first_choice] + list(choices)

Methods

convert_to_aliases

def convert_to_aliases() -> list[list[str | int]]

Converts arguments to a list of lists containing string or integer aliases.

Returns

list[list[str | int]] — The list of aliases.


ModelPrivateAttr

Bases: Representation

A descriptor for private attributes in class models.

Attributes

default

Default: default

default_factory

Default: default_factory

Methods

getattr

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.

Returns

Any

set_name

def __set_name__(cls: type[Any], name: str) -> None

Preserve __set_name__ protocol defined in https://peps.python.org/pep-0487.

Returns

None

get_default

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.

Returns

Any — The default value of the object.


ComputedFieldInfo

A container for data from @computed_field so that we can access it while building the pydantic-core schema.

Attributes

decorator_repr

Type: str Default: '@computed_field'

wrapped_property

Type: property

return_type

Type: Any

alias

Type: str | None

alias_priority

Type: int | None

title

Type: str | None

description

Type: str | None

repr

Type: bool


Field

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,
    include: bool | None = _Unset,
    discriminator: str | None = _Unset,
    json_schema_extra: dict[str, Any] | None = _Unset,
    frozen: bool | None = _Unset,
    validate_default: bool | None = _Unset,
    repr: bool = _Unset,
    init_var: bool | None = _Unset,
    kw_only: bool | None = _Unset,
    pattern: str | None = _Unset,
    strict: 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,
    extra: Unpack[_EmptyKwargs] = {},
) -> Any

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.

Returns

Any — The generated FieldInfo object

Parameters

default : Any Default: PydanticUndefined

Default value if the field is not set.

default_factory : typing.Callable[[], Any] | None Default: _Unset

A callable to generate the default value, such as :func:~datetime.utcnow.

alias : str | None Default: _Unset

An alternative name for the attribute.

alias_priority : int | None Default: _Unset

Priority of the alias. This affects whether an alias generator is used.

validation_alias : str | AliasPath | AliasChoices | None Default: _Unset

‘Whitelist’ validation step. The field will be the single one allowed by the alias or set of aliases defined.

serialization_alias : str | None Default: _Unset

‘Blacklist’ validation step. The vanilla field will be the single one of the alias’ or set of aliases’ fields and all the other fields will be ignored at serialization time.

title : str | None Default: _Unset

Human-readable title.

description : str | None Default: _Unset

Human-readable description.

examples : list[Any] | None Default: _Unset

Example values for this field.

exclude : bool | None Default: _Unset

Whether to exclude the field from the model schema.

include : bool | None Default: _Unset

Whether to include the field in the model schema.

discriminator : str | None Default: _Unset

Field name for discriminating the type in a tagged union.

json_schema_extra : dict[str, Any] | None Default: _Unset

Any additional JSON schema data for the schema property.

frozen : bool | None Default: _Unset

Whether the field is frozen.

validate_default : bool | None Default: _Unset

Run validation that isn’t only checking existence of defaults. True by default.

repr : bool Default: _Unset

A boolean indicating whether to include the field in the __repr__ output.

init_var : bool | None Default: _Unset

Whether the field should be included in the constructor of the dataclass.

kw_only : bool | None Default: _Unset

Whether the field should be a keyword-only argument in the constructor of the dataclass.

strict : bool | None Default: _Unset

If True, strict validation is applied to the field. See Strict Mode for details.

gt : float | None Default: _Unset

Greater than. If set, value must be greater than this. Only applicable to numbers.

ge : float | None Default: _Unset

Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.

lt : float | None Default: _Unset

Less than. If set, value must be less than this. Only applicable to numbers.

le : float | None Default: _Unset

Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.

multiple_of : float | None Default: _Unset

Value must be a multiple of this. Only applicable to numbers.

min_length : int | None Default: _Unset

Minimum length for strings.

max_length : int | None Default: _Unset

Maximum length for strings.

pattern : str | None Default: _Unset

Pattern for strings.

allow_inf_nan : bool | None Default: _Unset

Allow inf, -inf, nan. Only applicable to numbers.

max_digits : int | None Default: _Unset

Maximum number of allow digits for strings.

decimal_places : int | None Default: _Unset

Maximum number of decimal places allowed for numbers.

extra : Unpack[_EmptyKwargs] Default: \{\}

Include extra fields used by the JSON schema.


PrivateAttr

def PrivateAttr(
    default: Any = PydanticUndefined,
    default_factory: typing.Callable[[], Any] | None = None,
) -> Any

Indicates that attribute is only used internally and never mixed with regular fields.

Private attributes are not checked by Pydantic, so it’s up to you to maintain their accuracy.

Private attributes are stored in __private_attributes__ on the model.

Returns

Any — An instance of ModelPrivateAttr class.

Parameters

default : Any Default: PydanticUndefined

The attribute’s default value. Defaults to Undefined.

default_factory : typing.Callable[[], Any] | None Default: None

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.

Raises

  • ValueError — If both default and default_factory are set.

computed_field

def computed_field(
    return_type: Any = PydanticUndefined,
    alias: str | None = None,
    alias_priority: int | None = None,
    title: str | None = None,
    description: str | None = None,
    repr: bool = True,
) -> typing.Callable[[PropertyT], PropertyT]
def computed_field(__func: PropertyT) -> PropertyT

Decorator to include property and cached_property when serializing models.

If applied to functions not yet decorated with @property or @cached_property, the function is automatically wrapped with property.

See Computed Fields for more details.

Returns

PropertyT | typing.Callable[[PropertyT], PropertyT] — A proxy wrapper for the property.

Parameters

__f : PropertyT | None Default: None

the function to wrap.

alias : str | None Default: None

alias to use when serializing this computed field, only used when by_alias=True

alias_priority : int | None Default: None

priority of the alias. This affects whether an alias generator is used

title : str | None Default: None

Title to used when including this computed field in JSON Schema, currently unused waiting for #4697

description : str | None Default: None

Description to used when including this computed field in JSON Schema, defaults to the functions docstring, currently unused waiting for #4697

repr : bool Default: True

whether to include this computed field in model repr

return_type : Any Default: PydanticUndefined

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.


ReprArgs

Type: typing_extensions.TypeAlias Default: 'typing.Iterable[tuple[str | None, Any]]'

DeprecationWarning

Default: PydanticDeprecatedSince20

PropertyT

Default: typing.TypeVar('PropertyT')