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

Pydantic Dataclasses

Provide an enhanced dataclass that performs validation.

ConfigDict

Bases: TypedDict

A TypedDict for configuring Pydantic behaviour.

Attributes

title

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

Type: str | None

model_title_generator

A callable that takes a model class and returns the title for it. Defaults to None.

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

field_title_generator

A callable that takes a field’s name and info and returns title for it. Defaults to None.

Type: Callable[[str, FieldInfo | ComputedFieldInfo], 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. Defaults to 'ignore'.

You can configure how pydantic handles the attributes that are not defined in the model:

  • allow - Allow any extra attributes.
  • forbid - Forbid any extra attributes.
  • ignore - Ignore any extra attributes.
from pydantic import BaseModel, ConfigDict

class User(BaseModel):
  model_config = ConfigDict(extra='ignore')  # (1)

  name: str

user = User(name='John Doe', age=20)  # (2)
print(user)
#> name='John Doe'

This is the default behaviour.

The age argument is ignored.

Instead, with extra='allow', the age argument is included:

from pydantic import BaseModel, ConfigDict

class User(BaseModel):
  model_config = ConfigDict(extra='allow')

  name: str

user = User(name='John Doe', age=20)  # (1)
print(user)
#> name='John Doe' age=20

The age argument is included.

With extra='forbid', an error is raised:

from pydantic import BaseModel, ConfigDict, ValidationError

class User(BaseModel):
    model_config = ConfigDict(extra='forbid')

    name: str

try:
    User(name='John Doe', age=20)
except ValidationError as e:
    print(e)
    '''
    1 validation error for User
    age
      Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int]
    '''

Type: ExtraValues | None

frozen

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

from pydantic import BaseModel, ConfigDict, Field

class User(BaseModel):
  model_config = ConfigDict(populate_by_name=True)

  name: str = Field(alias='full_name')  # (1)
  age: int

user = User(full_name='John Doe', age=20)  # (2)
print(user)
#> name='John Doe' age=20
user = User(name='John Doe', age=20)  # (3)
print(user)
#> name='John Doe' age=20

The field 'name' has an alias 'full_name'.

The model is populated by the alias 'full_name'.

The model is populated by the field name 'name'.

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.

from enum import Enum
from typing import Optional

from pydantic import BaseModel, ConfigDict, Field

class SomeEnum(Enum):
    FOO = 'foo'
    BAR = 'bar'
    BAZ = 'baz'

class SomeModel(BaseModel):
    model_config = ConfigDict(use_enum_values=True)

    some_enum: SomeEnum
    another_enum: Optional[SomeEnum] = Field(
        default=SomeEnum.FOO, validate_default=True
    )

model1 = SomeModel(some_enum=SomeEnum.BAR)
print(model1.model_dump())
#> {'some_enum': 'bar', 'another_enum': 'foo'}

model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
print(model2.model_dump())
#> {'some_enum': 'bar', 'another_enum': 'baz'}

Type: bool

validate_assignment

Whether to validate the data when the model is changed. Defaults to False.

The default behavior of Pydantic is to validate the data when the model is created.

In case the user changes the data after the model is created, the model is not revalidated.

from pydantic import BaseModel

class User(BaseModel):
  name: str

user = User(name='John Doe')  # (1)
print(user)
#> name='John Doe'
user.name = 123  # (1)
print(user)
#> name=123

The validation happens only when the model is created.

The validation does not happen when the data is changed.

In case you want to revalidate the model when the data is changed, you can use validate_assignment=True:

from pydantic import BaseModel, ValidationError

class User(BaseModel, validate_assignment=True):  # (1)
  name: str

user = User(name='John Doe')  # (2)
print(user)
#> name='John Doe'
try:
  user.name = 123  # (3)
except ValidationError as e:
  print(e)
  '''
  1 validation error for User
  name
    Input should be a valid string [type=string_type, input_value=123, input_type=int]
  '''

You can either use class keyword arguments, or model_config to set validate_assignment=True.

The validation happens when the model is created.

The validation also happens when the data is changed.

Type: bool

arbitrary_types_allowed

Whether arbitrary types are allowed for field types. Defaults to False.

from pydantic import BaseModel, ConfigDict, ValidationError

# This is not a pydantic model, it's an arbitrary class
class Pet:
    def __init__(self, name: str):
        self.name = name

class Model(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)

    pet: Pet
    owner: str

pet = Pet(name='Hedwig')
# A simple check of instance type is used to validate the data
model = Model(owner='Harry', pet=pet)
print(model)
#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
print(model.pet)
#> <__main__.Pet object at 0x0123456789ab>
print(model.pet.name)
#> Hedwig
print(type(model.pet))
#> <class '__main__.Pet'>
try:
    # If the value is not an instance of the type, it's invalid
    Model(owner='Harry', pet='Hedwig')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    pet
      Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
    '''

# Nothing in the instance of the arbitrary type is checked
# Here name probably should have been a str, but it's not validated
pet2 = Pet(name=42)
model2 = Model(owner='Harry', pet=pet2)
print(model2)
#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
print(model2.pet)
#> <__main__.Pet object at 0x0123456789ab>
print(model2.pet.name)
#> 42
print(type(model2.pet))
#> <class '__main__.Pet'>

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 actual key provided in the data (e.g. 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 or an instance of AliasGenerator. Defaults to None.

When using a callable, the alias generator is used for both validation and serialization. If you want to use different alias generators for validation and serialization, you can use AliasGenerator instead.

If data source field names do not match your code style (e. g. CamelCase fields), you can automatically generate aliases using alias_generator. Here’s an example with a basic callable:

from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_pascal

class Voice(BaseModel):
    model_config = ConfigDict(alias_generator=to_pascal)

    name: str
    language_code: str

voice = Voice(Name='Filiz', LanguageCode='tr-TR')
print(voice.language_code)
#> tr-TR
print(voice.model_dump(by_alias=True))
#> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}

If you want to use different alias generators for validation and serialization, you can use AliasGenerator.

from pydantic import AliasGenerator, BaseModel, ConfigDict
from pydantic.alias_generators import to_camel, to_pascal

class Athlete(BaseModel):
    first_name: str
    last_name: str
    sport: str

    model_config = ConfigDict(
        alias_generator=AliasGenerator(
            validation_alias=to_camel,
            serialization_alias=to_pascal,
        )
    )

athlete = Athlete(firstName='John', lastName='Doe', sport='track')
print(athlete.model_dump(by_alias=True))
#> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}

Type: Callable[[str], str] | AliasGenerator | 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 and decimal fields. Defaults to True.

Type: bool

json_schema_extra

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

Type: JsonDict | 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.

By default, Pydantic attempts to coerce values to the correct type, when possible.

There are situations in which you may want to disable this behavior, and instead raise an error if a value’s type does not match the field’s type annotation.

To configure strict mode for all fields on a model, you can set strict=True on the model.

from pydantic import BaseModel, ConfigDict

class Model(BaseModel):
    model_config = ConfigDict(strict=True)

    name: str
    age: int

See Strict Mode for more details.

See the Conversion Table for more details on how Pydantic converts data in both strict and lax modes.

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

By default, model and dataclass instances are not revalidated during validation.

from typing import List

from pydantic import BaseModel

class User(BaseModel, revalidate_instances='never'):  # (1)
  hobbies: List[str]

class SubUser(User):
  sins: List[str]

class Transaction(BaseModel):
  user: User

my_user = User(hobbies=['reading'])
t = Transaction(user=my_user)
print(t)
#> user=User(hobbies=['reading'])

my_user.hobbies = [1]  # (2)
t = Transaction(user=my_user)  # (3)
print(t)
#> user=User(hobbies=[1])

my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
t = Transaction(user=my_sub_user)
print(t)
#> user=SubUser(hobbies=['scuba diving'], sins=['lying'])

revalidate_instances is set to 'never' by **default.

The assignment is not validated, unless you set validate_assignment to True in the model's config.

Since revalidate_instances is set to never, this is not revalidated.

If you want to revalidate instances during validation, you can set revalidate_instances to 'always' in the model’s config.

from typing import List

from pydantic import BaseModel, ValidationError

class User(BaseModel, revalidate_instances='always'):  # (1)
  hobbies: List[str]

class SubUser(User):
  sins: List[str]

class Transaction(BaseModel):
  user: User

my_user = User(hobbies=['reading'])
t = Transaction(user=my_user)
print(t)
#> user=User(hobbies=['reading'])

my_user.hobbies = [1]
try:
  t = Transaction(user=my_user)  # (2)
except ValidationError as e:
  print(e)
  '''
  1 validation error for Transaction
  user.hobbies.0
    Input should be a valid string [type=string_type, input_value=1, input_type=int]
  '''

my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
t = Transaction(user=my_sub_user)
print(t)  # (3)
#> user=User(hobbies=['scuba diving'])

revalidate_instances is set to 'always'.

The model is revalidated, since revalidate_instances is set to 'always'.

Using 'never' we would have gotten user=SubUser(hobbies=['scuba diving'], sins=['lying']).

It’s also possible to set revalidate_instances to 'subclass-instances' to only revalidate instances of subclasses of the model.

from typing import List

from pydantic import BaseModel

class User(BaseModel, revalidate_instances='subclass-instances'):  # (1)
  hobbies: List[str]

class SubUser(User):
  sins: List[str]

class Transaction(BaseModel):
  user: User

my_user = User(hobbies=['reading'])
t = Transaction(user=my_user)
print(t)
#> user=User(hobbies=['reading'])

my_user.hobbies = [1]
t = Transaction(user=my_user)  # (2)
print(t)
#> user=User(hobbies=[1])

my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
t = Transaction(user=my_sub_user)
print(t)  # (3)
#> user=User(hobbies=['scuba diving'])

revalidate_instances is set to 'subclass-instances'.

This is not revalidated, since my_user is not a subclass of User.

Using 'never' we would have gotten user=SubUser(hobbies=['scuba diving'], sins=['lying']).

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. Defaults to 'utf8'. Set equal to val_json_bytes to get back an equal value after serialization round trip.

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

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

val_json_bytes

The encoding of JSON serialized bytes to decode. Defaults to 'utf8'. Set equal to ser_json_bytes to get back an equal value after serialization round trip.

  • 'utf8' will deserialize UTF-8 strings to bytes.
  • 'base64' will deserialize URL safe base64 strings to bytes.
  • 'hex' will deserialize hexadecimal strings to bytes.

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

ser_json_inf_nan

The encoding of JSON serialized infinity and NaN float values. Defaults to 'null'.

  • 'null' will serialize infinity and NaN values as null.
  • 'constants' will serialize infinity and NaN values as Infinity and NaN.
  • 'strings' will serialize infinity as string "Infinity" and NaN as string "NaN".

Type: Literal['null', 'constants', 'strings']

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. Defaults to False.

Type: bool

protected_namespaces

A tuple of strings and/or patterns that prevent models from having fields with names that conflict with them. For strings, we match on a prefix basis. Ex, if ‘dog’ is in the protected namespace, ‘dog_name’ will be protected. For patterns, we match on the entire field name. Ex, if re.compile(r'^dog is in the protected namespace, 'dog' will be protected, but 'dog_name' will not be.) is in the protected namespace, ‘dog’ will be protected, but ‘dog_name’ will not be. Defaults to ('model_validate', 'model_dump',).

The reason we’ve selected these is to prevent collisions with other validation / dumping formats in the future - ex, model_validate_\{some_newly_supported_format\}.

Before v2.10, Pydantic used ('model_',) as the default value for this setting to prevent collisions between model attributes and BaseModel’s own methods. This was changed in v2.10 given feedback that this restriction was limiting in AI and data science contexts, where it is common to have fields with names like model_id, model_input, model_output, etc.

For more details, see https://github.com/pydantic/pydantic/issues/10315.

import warnings

from pydantic import BaseModel

warnings.filterwarnings('error')  # Raise warnings as errors

try:

    class Model(BaseModel):
        model_dump_something: str

except UserWarning as e:
    print(e)
    '''
    Field "model_dump_something" in Model has conflict with protected namespace "model_dump".

    You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('model_validate',)`.
    '''

You can customize this behavior using the protected_namespaces setting:

import re
import warnings

from pydantic import BaseModel, ConfigDict

with warnings.catch_warnings(record=True) as caught_warnings:
    warnings.simplefilter('always')  # Catch all warnings

    class Model(BaseModel):
        safe_field: str
        also_protect_field: str
        protect_this: str

        model_config = ConfigDict(
            protected_namespaces=(
                'protect_me_',
                'also_protect_',
                re.compile('^protect_this$'),
            )
        )

for warning in caught_warnings:
    print(f'{warning.message}')
    '''
    Field "also_protect_field" in Model has conflict with protected namespace "also_protect_".
    You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', re.compile('^protect_this$'))`.

    Field "protect_this" in Model has conflict with protected namespace "re.compile('^protect_this$')".
    You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', 'also_protect_')`.
    '''

While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision, an error is raised if there is an actual collision with an existing attribute:

from pydantic import BaseModel, ConfigDict

try:

    class Model(BaseModel):
        model_validate: str

        model_config = ConfigDict(protected_namespaces=('model_',))

except NameError as e:
    print(e)
    '''
    Field "model_validate" conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace "model_".
    '''

Type: tuple[str | Pattern[str], ...]

hide_input_in_errors

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

Pydantic shows the input value and type when it raises ValidationError during the validation.

from pydantic import BaseModel, ValidationError

class Model(BaseModel):
    a: str

try:
    Model(a=123)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    a
      Input should be a valid string [type=string_type, input_value=123, input_type=int]
    '''

You can hide the input value and type by setting the hide_input_in_errors config to True.

from pydantic import BaseModel, ConfigDict, ValidationError

class Model(BaseModel):
    a: str
    model_config = ConfigDict(hide_input_in_errors=True)

try:
    Model(a=123)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    a
      Input should be a valid string [type=string_type]
    '''

Type: bool

defer_build

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

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

Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances.

Type: bool

plugin_settings

A dict of settings for plugins. Defaults to None.

Type: dict[str, object] | None

schema_generator

Type: type[_GenerateSchema] | None

json_schema_serialization_defaults_required

Whether fields with default values should be marked as required in the serialization schema. Defaults to False.

This ensures that the serialization schema will reflect the fact a field with a default will always be present when serializing the model, even though it is not required for validation.

However, there are scenarios where this may be undesirable — in particular, if you want to share the schema between validation and serialization, and don’t mind fields with defaults being marked as not required during serialization. See #7209 for more details.

from pydantic import BaseModel, ConfigDict

class Model(BaseModel):
    a: str = 'a'

    model_config = ConfigDict(json_schema_serialization_defaults_required=True)

print(Model.model_json_schema(mode='validation'))
'''
{
    'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
    'title': 'Model',
    'type': 'object',
}
'''
print(Model.model_json_schema(mode='serialization'))
'''
{
    'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
    'required': ['a'],
    'title': 'Model',
    'type': 'object',
}
'''

Type: bool

json_schema_mode_override

If not None, the specified mode will be used to generate the JSON schema regardless of what mode was passed to the function call. Defaults to None.

This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the validation schema.

It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation and serialization that must both be referenced from the same schema; when this happens, we automatically append -Input to the definition reference for the validation schema and -Output to the definition reference for the serialization schema. By specifying a json_schema_mode_override though, this prevents the conflict between the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes from being added to the definition references.

from pydantic import BaseModel, ConfigDict, Json

class Model(BaseModel):
    a: Json[int]  # requires a string to validate, but will dump an int

print(Model.model_json_schema(mode='serialization'))
'''
{
    'properties': {'a': {'title': 'A', 'type': 'integer'}},
    'required': ['a'],
    'title': 'Model',
    'type': 'object',
}
'''

class ForceInputModel(Model):
    # the following ensures that even with mode='serialization', we
    # will get the schema that would be generated for validation.
    model_config = ConfigDict(json_schema_mode_override='validation')

print(ForceInputModel.model_json_schema(mode='serialization'))
'''
{
    'properties': {
        'a': {
            'contentMediaType': 'application/json',
            'contentSchema': {'type': 'integer'},
            'title': 'A',
            'type': 'string',
        }
    },
    'required': ['a'],
    'title': 'ForceInputModel',
    'type': 'object',
}
'''

Type: Literal['validation', 'serialization', None]

coerce_numbers_to_str

If True, enables automatic coercion of any Number type to str in “lax” (non-strict) mode. Defaults to False.

Pydantic doesn’t allow number types (int, float, Decimal) to be coerced as type str by default.

from decimal import Decimal

from pydantic import BaseModel, ConfigDict, ValidationError

class Model(BaseModel):
    value: str

try:
    print(Model(value=42))
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    value
      Input should be a valid string [type=string_type, input_value=42, input_type=int]
    '''

class Model(BaseModel):
    model_config = ConfigDict(coerce_numbers_to_str=True)

    value: str

repr(Model(value=42).value)
#> "42"
repr(Model(value=42.13).value)
#> "42.13"
repr(Model(value=Decimal('42.13')).value)
#> "42.13"

Type: bool

regex_engine

The regex engine to be used for pattern validation. Defaults to 'rust-regex'.

  • rust-regex uses the regex Rust crate, which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
  • python-re use the re module, which supports all regex features, but may be slower.
from pydantic import BaseModel, ConfigDict, Field, ValidationError

class Model(BaseModel):
    model_config = ConfigDict(regex_engine='python-re')

    value: str = Field(pattern=r'^abc(?=def)')

print(Model(value='abcdef').value)
#> abcdef

try:
    print(Model(value='abxyzcdef'))
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    value
      String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
    '''

Type: Literal['rust-regex', 'python-re']

validation_error_cause

If True, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False.

Type: bool

use_attribute_docstrings

Whether docstrings of attributes (bare string literals immediately following the attribute declaration) should be used for field descriptions. Defaults to False.

Available in Pydantic v2.7+.

from pydantic import BaseModel, ConfigDict, Field


class Model(BaseModel):
    model_config = ConfigDict(use_attribute_docstrings=True)

    x: str
    """
    Example of an attribute docstring
    """

    y: int = Field(description="Description in Field")
    """
    Description in Field overrides attribute docstring
    """


print(Model.model_fields["x"].description)
# > Example of an attribute docstring
print(Model.model_fields["y"].description)
# > Description in Field

This requires the source code of the class to be available at runtime.

Type: bool

cache_strings

Whether to cache strings to avoid constructing new Python objects. Defaults to True.

Enabling this setting should significantly improve validation performance while increasing memory usage slightly.

  • True or 'all' (the default): cache all strings
  • 'keys': cache only dictionary keys
  • False or 'none': no caching

Type: bool | Literal['all', 'keys', 'none']


PydanticUserError

Bases: PydanticErrorMixin, TypeError

An error raised due to incorrect use of Pydantic.


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: Callable[[], Any] | Callable[[dict[str, Any]], 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)

field_title_generator

Type: Callable[[str, FieldInfo], str] | None Default: kwargs.pop('field_title_generator', 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)

discriminator

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

deprecated

Type: Deprecated | str | bool | None Default: kwargs.pop('deprecated', getattr(self, 'deprecated', None))

json_schema_extra

Type: JsonDict | Callable[[JsonDict], None] | 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

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

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, 'union_mode': None, 'coerce_numbers_to_str': None, 'fail_fast': types.FailFast\}

evaluated

Default: False

deprecation_message

The deprecation message to be emitted, or None if not set.

Type: str | None

default_factory_takes_validated_data

Whether the provided default factory callable has a validated data parameter.

Returns None if no default factory is set.

Type: bool | 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

@staticmethod

def from_field(
    default: Any = PydanticUndefined,
    kwargs: Unpack[_FromFieldInfoInputs] = {},
) -> FieldInfo

Create a new FieldInfo object with the Field function.

Returns

FieldInfo — 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

@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)]
Returns

FieldInfo — An instance of the field metadata.

Parameters

annotation : type[Any]

An annotation object.

from_annotated_attribute

@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
Returns

FieldInfo — 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.

Later FieldInfo instances override earlier ones.

Returns

FieldInfo — A merged FieldInfo instance.

get_default

def get_default(
    call_default_factory: Literal[True],
    validated_data: dict[str, Any] | None = None,
) -> Any
def get_default(call_default_factory: Literal[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.

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

The already validated data to be passed to the default factory.

is_required

def is_required() -> bool

Check if the field is required (i.e., does not have a default value or factory).

Returns

boolTrue if the field is required, False otherwise.

rebuild_annotation

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.

Returns

Any — The rebuilt annotation.

apply_typevars_map

def apply_typevars_map(
    typevars_map: dict[Any, Any] | None,
    globalns: GlobalsNamespace | None = None,
    localns: MappingNamespace | None = 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.

globalns : GlobalsNamespace | None Default: None

The globals namespace to use during type annotation evaluation.

localns : MappingNamespace | None Default: None

The locals namespace to use during type annotation evaluation.


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: ellipsis,
    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,
    field_title_generator: Callable[[str, FieldInfo], 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 | 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: annotated_types.SupportsGt | None = _Unset,
    ge: annotated_types.SupportsGe | None = _Unset,
    lt: annotated_types.SupportsLt | None = _Unset,
    le: annotated_types.SupportsLe | 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,
    fail_fast: bool | None = _Unset,
    extra: Unpack[_EmptyKwargs] = {},
) -> Any
def Field(
    default: _T,
    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,
    field_title_generator: Callable[[str, FieldInfo], 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 | 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: annotated_types.SupportsGt | None = _Unset,
    ge: annotated_types.SupportsGe | None = _Unset,
    lt: annotated_types.SupportsLt | None = _Unset,
    le: annotated_types.SupportsLe | 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,
    fail_fast: bool | None = _Unset,
    extra: Unpack[_EmptyKwargs] = {},
) -> _T
def Field(
    default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
    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,
    field_title_generator: Callable[[str, FieldInfo], 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 | 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: annotated_types.SupportsGt | None = _Unset,
    ge: annotated_types.SupportsGe | None = _Unset,
    lt: annotated_types.SupportsLt | None = _Unset,
    le: annotated_types.SupportsLe | 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,
    fail_fast: bool | None = _Unset,
    extra: Unpack[_EmptyKwargs] = {},
) -> _T
def Field(
    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,
    field_title_generator: Callable[[str, FieldInfo], 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 | 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: annotated_types.SupportsGt | None = _Unset,
    ge: annotated_types.SupportsGe | None = _Unset,
    lt: annotated_types.SupportsLt | None = _Unset,
    le: annotated_types.SupportsLe | 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,
    fail_fast: bool | None = _Unset,
    extra: Unpack[_EmptyKwargs] = {},
) -> Any

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

Returns

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

Parameters

default : Any Default: PydanticUndefined

Default value if the field is not set.

default_factory : Callable[[], Any] | Callable[[dict[str, Any]], Any] | None Default: _Unset

A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data.

alias : str | None Default: _Unset

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.

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

Like alias, but only affects validation, not serialization.

serialization_alias : str | None Default: _Unset

Like alias, but only affects serialization, not validation.

title : str | None Default: _Unset

Human-readable title.

field_title_generator : Callable[[str, FieldInfo], str] | None Default: _Unset

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

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 | types.Discriminator | None Default: _Unset

Field name or Discriminator for discriminating the type in a tagged union.

deprecated : Deprecated | str | bool | None Default: _Unset

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.

json_schema_extra : JsonDict | Callable[[JsonDict], None] | None Default: _Unset

A dict or callable to provide extra JSON schema properties.

frozen : bool | None Default: _Unset

Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.

validate_default : bool | None Default: _Unset

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.

repr : bool Default: _Unset

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

init : bool | None Default: _Unset

Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)

init_var : bool | None Default: _Unset

Whether the field should only be included in the constructor of the dataclass. (Only applies to dataclasses.)

kw_only : bool | None Default: _Unset

Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)

coerce_numbers_to_str : bool | None Default: _Unset

Whether to enable coercion of any Number type to str (not applicable in strict mode).

strict : bool | None Default: _Unset

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

gt : annotated_types.SupportsGt | None Default: _Unset

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

ge : annotated_types.SupportsGe | None Default: _Unset

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

lt : annotated_types.SupportsLt | None Default: _Unset

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

le : annotated_types.SupportsLe | 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 iterables.

max_length : int | None Default: _Unset

Maximum length for iterables.

pattern : str | typing.Pattern[str] | None Default: _Unset

Pattern for strings (a regular expression).

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.

fail_fast : bool | None Default: _Unset

If True, validation will stop on the first error. If False, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset).

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

(Deprecated) Extra fields that will be included in the JSON schema.


PrivateAttr

def PrivateAttr(default: _T, init: Literal[False] = False) -> _T
def PrivateAttr(default_factory: Callable[[], _T], init: Literal[False] = False) -> _T
def PrivateAttr(init: Literal[False] = False) -> Any

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

Returns

Any — An instance of ModelPrivateAttr class.

Parameters

default : Any Default: PydanticUndefined

The attribute’s default value. Defaults to Undefined.

default_factory : 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.

init : Literal[False] Default: False

Whether the attribute should be included in the constructor of the dataclass. Always False.

Raises

  • ValueError — If both default and default_factory are set.

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 | None = None,
    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 | None = None,
    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 | None = None,
    config: ConfigDict | type[object] | None = None,
    validate_on_init: bool | None = None,
) -> type[PydanticDataclass]

Usage docs: https://docs.pydantic.dev/2.10/concepts/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 to include the field in the __repr__ output.

eq : bool Default: True

Determines if a __eq__ method 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 a __hash__ method should be included in the class, as in dataclasses.dataclass.

frozen : bool | None Default: None

Determines if the generated class should be a ‘frozen’ dataclass, which does not allow its attributes to be modified after it has been initialized. If not set, the value from the provided config argument will be used (and will default to False otherwise).

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

The Pydantic config to use for the dataclass.

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: MappingNamespace | 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 rebuild the pydantic-core schema for.

force : bool Default: False

Whether to force the rebuilding of the 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 : MappingNamespace | None Default: None

The types namespace, defaults to None.


is_pydantic_dataclass

def is_pydantic_dataclass(class_: type[Any]) -> TypeGuard[type[PydanticDataclass]]

Whether a class is a pydantic dataclass.

Returns

TypeGuard[type[PydanticDataclass]]True if the class is a pydantic dataclass, False otherwise.

Parameters

class_ : type[Any]

The class.


MappingNamespace

Any kind of namespace.

In most cases, this is a local namespace (e.g. the __dict__ attribute of a class, the f_locals attribute of a frame object, when dealing with types defined inside functions). This namespace type is expected as the locals argument during annotations evaluation.

Type: TypeAlias Default: Mapping[str, Any]