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

Pydantic Dataclasses

Provide an enhanced dataclass that performs validation.

ConfigDict

Bases: TypedDict

Usage docs: https://docs.pydantic.dev/2.2/usage/model_config/

A TypedDict for configuring Pydantic behaviour.

Attributes

title

The title for the generated JSON schema, defaults to the model’s name

Type: str | None

str_to_lower

Whether to convert all characters to lowercase for str types. Defaults to False.

Type: bool

str_to_upper

Whether to convert all characters to uppercase for str types. Defaults to False.

Type: bool

str_strip_whitespace

Whether to strip leading and trailing whitespace for str types.

Type: bool

str_min_length

The minimum length for str types. Defaults to None.

Type: int

str_max_length

The maximum length for str types. Defaults to None.

Type: int | None

extra

Whether to ignore, allow, or forbid extra attributes during model initialization.

The value must be a ExtraValues string. Defaults to 'ignore'.

See Extra Attributes for details.

Type: ExtraValues | None

frozen

Whether or not models are faux-immutable, i.e. whether __setattr__ is allowed, and also generates a __hash__() method for the model. This makes instances of the model potentially hashable if all the attributes are hashable. Defaults to False.

Type: bool

populate_by_name

Whether an aliased field may be populated by its name as given by the model attribute, as well as the alias. Defaults to False.

Type: bool

use_enum_values

Whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialize model.model_dump() later. Defaults to False.

Type: bool

validate_assignment

Type: bool

arbitrary_types_allowed

Type: bool

from_attributes

Whether to build models and look up discriminators of tagged unions using python object attributes.

Type: bool

loc_by_alias

Whether to use the alias for error locs rather than the field’s name. Defaults to True.

Type: bool

alias_generator

A callable that takes a field name and returns an alias for it.

See Alias Generator for details.

Type: Callable[[str], str] | None

ignored_types

A tuple of types that may occur as values of class attributes without annotations. This is typically used for custom descriptors (classes that behave like property). If an attribute is set on a class without an annotation and has a type that is not in this tuple (or otherwise recognized by pydantic), an error will be raised. Defaults to ().

Type: tuple[type, ...]

allow_inf_nan

Whether to allow infinity (+inf an -inf) and NaN values to float fields. Defaults to True.

Type: bool

json_schema_extra

A dict or callable to provide extra JSON schema properties. Defaults to None.

Type: dict[str, object] | JsonSchemaExtraCallable | None

json_encoders

A dict of custom JSON encoders for specific types. Defaults to None.

Type: dict[type[object], JsonEncoder] | None

strict

(new in V2) If True, strict validation is applied to all fields on the model. See Strict Mode for details.

Type: bool

revalidate_instances

When and how to revalidate models and dataclasses during validation. Accepts the string values of 'never', 'always' and 'subclass-instances'. Defaults to 'never'.

  • 'never' will not revalidate models and dataclasses during validation
  • 'always' will revalidate models and dataclasses during validation
  • 'subclass-instances' will revalidate models and dataclasses during validation if the instance is a subclass of the model or dataclass

See Revalidate Instances for details.

Type: Literal['always', 'never', 'subclass-instances']

ser_json_timedelta

The format of JSON serialized timedeltas. Accepts the string values of 'iso8601' and 'float'. Defaults to 'iso8601'.

  • 'iso8601' will serialize timedeltas to ISO 8601 durations.
  • 'float' will serialize timedeltas to the total number of seconds.

Type: Literal['iso8601', 'float']

ser_json_bytes

The encoding of JSON serialized bytes. Accepts the string values of 'utf8' and 'base64'. Defaults to 'utf8'.

  • 'utf8' will serialize bytes to UTF-8 strings.
  • 'base64' will serialize bytes to URL safe base64 strings.

Type: Literal['utf8', 'base64']

validate_default

Whether to validate default values during validation. Defaults to False.

Type: bool

validate_return

whether to validate the return value from call validators.

Type: bool

protected_namespaces

A tuple of strings that prevent model to have field which conflict with them. Defaults to ('model_', )).

See Protected Namespaces for details.

Type: tuple[str, ...]

hide_input_in_errors

Whether to hide inputs when printing errors. Defaults to False.

See Hide Input in Errors.

Type: bool

defer_build

Whether to defer model validator and serializer construction until the first model validation.

This can be useful to avoid the overhead of building models which are only used nested within other models, or when you want to manually define type namespace via Model.model_rebuild(_types_namespace=...). Defaults to False.

Type: bool

schema_generator

A custom core schema generator class to use when generating JSON schemas. Useful if you want to change the way types are validated across an entire model/schema.

The GenerateSchema interface is subject to change, currently only the string_schema method is public.

See #6737 for details.

Defaults to None.

Type: type[_GenerateSchema] | None


PydanticDataclass

Bases: StandardDataclass, Protocol

A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass.


getattr_migration

def getattr_migration(module: str) -> Callable[[str], Any]

Implement PEP 562 for objects that were either moved or removed on the migration to V2.

Returns

Callable[[str], Any] — A callable that will raise an error if the object is not found.

Parameters

module : str

The module name.


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,
    discriminator: str | None = _Unset,
    json_schema_extra: dict[str, Any] | typing.Callable[[dict[str, Any]], None] | 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,
    union_mode: Literal['smart', 'left_to_right'] = _Unset,
    extra: Unpack[_EmptyKwargs] = {},
) -> Any

Usage docs: https://docs.pydantic.dev/2.2/usage/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.

Returns

Any — A new FieldInfo, the return annotation is Any so Field can be used on type annotated fields without causing a typing error.

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

discriminator : str | None Default: _Unset

Field name for discriminating the type in a tagged union.

json_schema_extra : dict[str, Any] | typing.Callable[[dict[str, Any]], None] | 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. This can be set to True or False. If not set, it defaults to None.

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.

union_mode : Literal['smart', 'left_to_right'] Default: _Unset

The strategy to apply when validating a union. Can be smart (the default), or left_to_right. See Union Mode for details.

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

Include extra fields used by the JSON schema.


dataclass

def dataclass(
    init: Literal[False] = False,
    repr: bool = True,
    eq: bool = True,
    order: bool = False,
    unsafe_hash: bool = False,
    frozen: bool = False,
    config: ConfigDict | type[object] | None = None,
    validate_on_init: bool | None = None,
    kw_only: bool = ...,
    slots: bool = ...,
) -> Callable[[type[_T]], type[PydanticDataclass]]
def dataclass(
    _cls: type[_T],
    init: Literal[False] = False,
    repr: bool = True,
    eq: bool = True,
    order: bool = False,
    unsafe_hash: bool = False,
    frozen: bool = False,
    config: ConfigDict | type[object] | None = None,
    validate_on_init: bool | None = None,
    kw_only: bool = ...,
    slots: bool = ...,
) -> type[PydanticDataclass]
def dataclass(
    init: Literal[False] = False,
    repr: bool = True,
    eq: bool = True,
    order: bool = False,
    unsafe_hash: bool = False,
    frozen: bool = False,
    config: ConfigDict | type[object] | None = None,
    validate_on_init: bool | None = None,
) -> Callable[[type[_T]], type[PydanticDataclass]]
def dataclass(
    _cls: type[_T],
    init: Literal[False] = False,
    repr: bool = True,
    eq: bool = True,
    order: bool = False,
    unsafe_hash: bool = False,
    frozen: bool = False,
    config: ConfigDict | type[object] | None = None,
    validate_on_init: bool | None = None,
) -> type[PydanticDataclass]

Usage docs: https://docs.pydantic.dev/2.2/usage/dataclasses/

A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python dataclass, but with added validation.

This function should be used similarly to dataclasses.dataclass.

Returns

Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass] — A decorator that accepts a class as its argument and returns a Pydantic dataclass.

Parameters

_cls : type[_T] | None Default: None

The target dataclass.

init : Literal[False] Default: False

Included for signature compatibility with dataclasses.dataclass, and is passed through to dataclasses.dataclass when appropriate. If specified, must be set to False, as pydantic inserts its own __init__ function.

repr : bool Default: True

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

eq : bool Default: True

Determines if a __eq__ should be generated for the class.

order : bool Default: False

Determines if comparison magic methods should be generated, such as __lt__, but not __eq__.

unsafe_hash : bool Default: False

Determines if an unsafe hashing function should be included in the class.

frozen : bool Default: False

Determines if the generated class should be a ‘frozen’ dataclass, which does not allow its attributes to be modified from its constructor.

config : ConfigDict | type[object] | None Default: None

A configuration for the dataclass generation.

validate_on_init : bool | None Default: None

A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses are validated on init.

kw_only : bool Default: False

Determines if __init__ method parameters must be specified by keyword only. Defaults to False.

slots : bool Default: False

Determines if the generated class should be a ‘slots’ dataclass, which does not allow the addition of new attributes after instantiation.

Raises

  • AssertionError — Raised if init is not False or validate_on_init is False.

rebuild_dataclass

def rebuild_dataclass(
    cls: type[PydanticDataclass],
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the dataclass.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

This is analogous to BaseModel.model_rebuild.

Returns

bool | None — Returns None if the schema is already “complete” and rebuilding was not required. bool | None — If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Parameters

cls : type[PydanticDataclass]

The class to build the dataclass core schema for.

force : bool Default: False

Whether to force the rebuilding of the model schema, defaults to False.

raise_errors : bool Default: True

Whether to raise errors, defaults to True.

_parent_namespace_depth : int Default: 2

The depth level of the parent namespace, defaults to 2.

_types_namespace : dict[str, Any] | None Default: None

The types namespace, defaults to None.