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

pydantic

Logic for creating models.

ConfigDict

Bases: TypedDict

A dictionary-like class for configuring Pydantic models.

Attributes

title

Type: str | None

str_to_lower

Type: bool

str_to_upper

Type: bool

str_strip_whitespace

Type: bool

str_min_length

Type: int

str_max_length

Type: int | None

extra

Type: ExtraValues | None

frozen

Type: bool

populate_by_name

Type: bool

use_enum_values

Type: bool

validate_assignment

Type: bool

arbitrary_types_allowed

Type: bool

from_attributes

Type: bool

loc_by_alias

Type: bool

alias_generator

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

ignored_types

Type: tuple[type, ...]

allow_inf_nan

Type: bool

json_schema_extra

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

strict

Type: bool

revalidate_instances

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

ser_json_timedelta

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

ser_json_bytes

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

validate_default

Type: bool

validate_return

Type: bool

protected_namespaces

Type: tuple[str, ...]

hide_input_in_errors

Type: bool


PydanticUndefinedAnnotation

Bases: PydanticErrorMixin, NameError

A subclass of NameError raised when handling undefined annotations during CoreSchema generation.

Attributes

name

Default: name

Methods

from_name_error

@classmethod

def from_name_error(cls, name_error: NameError) -> Self

Convert a NameError to a PydanticUndefinedAnnotation error.

Returns

Self — Converted PydanticUndefinedAnnotation error.

Parameters

name_error : NameError

NameError to be converted.


PydanticUserError

Bases: PydanticErrorMixin, TypeError

An error raised due to incorrect use of Pydantic.


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


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.


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.


GenerateJsonSchema

A class for generating JSON schemas.

This class generates JSON schemas based on configured parameters. The default schema dialect is ‘https://json-schema.org/draft/2020-12/schema’. The class uses by_alias to configure how fields with multiple names are handled and ref_template to format reference names.

Constructor Parameters

by_alias : bool Default: True

Whether or not to include field names.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The format string to use when generating reference names.

Attributes

schema_dialect

Default: 'https://json-schema.org/draft/2020-12/schema'

ignored_warning_kinds

Type: set[JsonSchemaWarningKind] Default: \{'skipped-choice'\}

by_alias

Default: by_alias

ref_template

Default: ref_template

core_to_json_refs

Type: dict[CoreModeRef, JsonRef] Default: \{\}

core_to_defs_refs

Type: dict[CoreModeRef, DefsRef] Default: \{\}

defs_to_core_refs

Type: dict[DefsRef, CoreModeRef] Default: \{\}

json_to_defs_refs

Type: dict[JsonRef, DefsRef] Default: \{\}

definitions

Type: dict[DefsRef, JsonSchemaValue] Default: \{\}

mode

Type: JsonSchemaMode Default: 'validation'

Methods

build_schema_type_to_method

def build_schema_type_to_method(

) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]

Builds a dictionary mapping fields to methods for generating JSON schemas.

Returns

dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] — A dictionary containing the mapping of CoreSchemaOrFieldType to a handler method.

Raises
  • TypeError — If no method has been defined for generating a JSON schema for a given pydantic core schema type.

generate_definitions

def generate_definitions(
    inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]],
) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]

Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a mapping that links the input keys to the definition references.

Returns

tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]] — A tuple where:

  • The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have JsonRef references to definitions that are defined in the second returned element.)
  • The second element is a dictionary whose keys are definition references for the JSON schemas from the first returned element, and whose values are the actual JSON schema definitions.
Parameters

inputs : Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]

A sequence of tuples, where:

  • The first element is a JSON schema key type.
  • The second element is the JSON mode: either ‘validation’ or ‘serialization’.
  • The third element is a core schema.
Raises
  • PydanticUserError — Raised if the JSON schema generator has already been used to generate a JSON schema.

generate

def generate(schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue

Generates a JSON schema for a specified schema in a specified mode.

Returns

JsonSchemaValue — A JSON schema representing the specified schema.

Parameters

schema : CoreSchema

A Pydantic model.

mode : JsonSchemaMode Default: 'validation'

The mode in which to generate the schema. Defaults to ‘validation’.

Raises
  • PydanticUserError — If the JSON schema generator has already been used to generate a JSON schema.

generate_inner

def generate_inner(schema: CoreSchemaOrField) -> JsonSchemaValue

Generates a JSON schema for a given core schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : CoreSchemaOrField

The given core schema.

any_schema

def any_schema(schema: core_schema.AnySchema) -> JsonSchemaValue

Generates a JSON schema that matches any value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.AnySchema

The core schema.

none_schema

def none_schema(schema: core_schema.NoneSchema) -> JsonSchemaValue

Generates a JSON schema that matches a None value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.NoneSchema

The core schema.

bool_schema

def bool_schema(schema: core_schema.BoolSchema) -> JsonSchemaValue

Generates a JSON schema that matches a bool value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.BoolSchema

The core schema.

int_schema

def int_schema(schema: core_schema.IntSchema) -> JsonSchemaValue

Generates a JSON schema that matches an Int value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.IntSchema

The core schema.

float_schema

def float_schema(schema: core_schema.FloatSchema) -> JsonSchemaValue

Generates a JSON schema that matches a float value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.FloatSchema

The core schema.

str_schema

def str_schema(schema: core_schema.StringSchema) -> JsonSchemaValue

Generates a JSON schema that matches a string value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.StringSchema

The core schema.

bytes_schema

def bytes_schema(schema: core_schema.BytesSchema) -> JsonSchemaValue

Generates a JSON schema that matches a bytes value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.BytesSchema

The core schema.

date_schema

def date_schema(schema: core_schema.DateSchema) -> JsonSchemaValue

Generates a JSON schema that matches a date value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DateSchema

The core schema.

time_schema

def time_schema(schema: core_schema.TimeSchema) -> JsonSchemaValue

Generates a JSON schema that matches a time value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TimeSchema

The core schema.

datetime_schema

def datetime_schema(schema: core_schema.DatetimeSchema) -> JsonSchemaValue

Generates a JSON schema that matches a datetime value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DatetimeSchema

The core schema.

timedelta_schema

def timedelta_schema(schema: core_schema.TimedeltaSchema) -> JsonSchemaValue

Generates a JSON schema that matches a timedelta value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TimedeltaSchema

The core schema.

literal_schema

def literal_schema(schema: core_schema.LiteralSchema) -> JsonSchemaValue

Generates a JSON schema that matches a literal value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.LiteralSchema

The core schema.

is_instance_schema

def is_instance_schema(schema: core_schema.IsInstanceSchema) -> JsonSchemaValue

Generates a JSON schema that checks if a value is an instance of a class, equivalent to Python’s isinstance method.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.IsInstanceSchema

The core schema.

is_subclass_schema

def is_subclass_schema(schema: core_schema.IsSubclassSchema) -> JsonSchemaValue

Generates a JSON schema that checks if a value is a subclass of a class, equivalent to Python’s issubclass method.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.IsSubclassSchema

The core schema.

callable_schema

def callable_schema(schema: core_schema.CallableSchema) -> JsonSchemaValue

Generates a JSON schema that matches a callable value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.CallableSchema

The core schema.

list_schema

def list_schema(schema: core_schema.ListSchema) -> JsonSchemaValue

Returns a schema that matches a list schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ListSchema

The core schema.

tuple_positional_schema

def tuple_positional_schema(
    schema: core_schema.TuplePositionalSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a positional tuple schema e.g. Tuple[int, str, bool].

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TuplePositionalSchema

The core schema.

tuple_variable_schema

def tuple_variable_schema(schema: core_schema.TupleVariableSchema) -> JsonSchemaValue

Generates a JSON schema that matches a variable tuple schema e.g. Tuple[int, ...].

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TupleVariableSchema

The core schema.

set_schema

def set_schema(schema: core_schema.SetSchema) -> JsonSchemaValue

Generates a JSON schema that matches a set schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.SetSchema

The core schema.

frozenset_schema

def frozenset_schema(schema: core_schema.FrozenSetSchema) -> JsonSchemaValue

Generates a JSON schema that matches a frozenset schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.FrozenSetSchema

The core schema.

generator_schema

def generator_schema(schema: core_schema.GeneratorSchema) -> JsonSchemaValue

Returns a JSON schema that represents the provided GeneratorSchema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.GeneratorSchema

The schema.

dict_schema

def dict_schema(schema: core_schema.DictSchema) -> JsonSchemaValue

Generates a JSON schema that matches a dict schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DictSchema

The core schema.

function_before_schema

def function_before_schema(
    schema: core_schema.BeforeValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-before schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.BeforeValidatorFunctionSchema

The core schema.

function_after_schema

def function_after_schema(
    schema: core_schema.AfterValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-after schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.AfterValidatorFunctionSchema

The core schema.

function_plain_schema

def function_plain_schema(
    schema: core_schema.PlainValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-plain schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.PlainValidatorFunctionSchema

The core schema.

function_wrap_schema

def function_wrap_schema(
    schema: core_schema.WrapValidatorFunctionSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a function-wrap schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.WrapValidatorFunctionSchema

The core schema.

default_schema

def default_schema(schema: core_schema.WithDefaultSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema with a default value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.WithDefaultSchema

The core schema.

nullable_schema

def nullable_schema(schema: core_schema.NullableSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows null values.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.NullableSchema

The core schema.

union_schema

def union_schema(schema: core_schema.UnionSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching any of the given schemas.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.UnionSchema

The core schema.

tagged_union_schema

def tagged_union_schema(schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where the schemas are tagged with a discriminator field that indicates which schema should be used to validate the value.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TaggedUnionSchema

The core schema.

chain_schema

def chain_schema(schema: core_schema.ChainSchema) -> JsonSchemaValue

Generates a JSON schema that matches a core_schema.ChainSchema.

When generating a schema for validation, we return the validation JSON schema for the first step in the chain. For serialization, we return the serialization JSON schema for the last step in the chain.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ChainSchema

The core schema.

lax_or_strict_schema

def lax_or_strict_schema(schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching either the lax schema or the strict schema.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.LaxOrStrictSchema

The core schema.

json_or_python_schema

def json_or_python_schema(schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the Python schema.

The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override this method.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.JsonOrPythonSchema

The core schema.

typed_dict_schema

def typed_dict_schema(schema: core_schema.TypedDictSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a typed dict.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TypedDictSchema

The core schema.

typed_dict_field_schema

def typed_dict_field_schema(schema: core_schema.TypedDictField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a typed dict field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.TypedDictField

The core schema.

dataclass_field_schema

def dataclass_field_schema(schema: core_schema.DataclassField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a dataclass field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DataclassField

The core schema.

model_field_schema

def model_field_schema(schema: core_schema.ModelField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a model field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ModelField

The core schema.

computed_field_schema

def computed_field_schema(schema: core_schema.ComputedField) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a computed field.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ComputedField

The core schema.

model_schema

def model_schema(schema: core_schema.ModelSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a model.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ModelSchema

The core schema.

resolve_schema_to_update

def resolve_schema_to_update(json_schema: JsonSchemaValue) -> JsonSchemaValue

Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.

Returns

JsonSchemaValue — The resolved schema.

Parameters

json_schema : JsonSchemaValue

The schema to resolve.

model_fields_schema

def model_fields_schema(schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a model’s fields.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ModelFieldsSchema

The core schema.

field_is_present

def field_is_present(field: CoreSchemaField) -> bool

Whether the field should be included in the generated JSON schema.

Returns

boolTrue if the field should be included in the generated JSON schema, False otherwise.

Parameters

field : CoreSchemaField

The schema for the field itself.

field_is_required

def field_is_required(
    field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
    total: bool,
) -> bool

Whether the field should be marked as required in the generated JSON schema. (Note that this is irrelevant if the field is not present in the JSON schema.).

Returns

boolTrue if the field should be marked as required in the generated JSON schema, False otherwise.

Parameters

field : core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField

The schema for the field itself.

total : bool

Only applies to TypedDictFields. Indicates if the TypedDict this field belongs to is total, in which case any fields that don’t explicitly specify required=False are required.

dataclass_args_schema

def dataclass_args_schema(schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a dataclass’s constructor arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DataclassArgsSchema

The core schema.

dataclass_schema

def dataclass_schema(schema: core_schema.DataclassSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a dataclass.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DataclassSchema

The core schema.

arguments_schema

def arguments_schema(schema: core_schema.ArgumentsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.ArgumentsSchema

The core schema.

kw_arguments_schema

def kw_arguments_schema(
    arguments: list[core_schema.ArgumentsParameter],
    var_kwargs_schema: CoreSchema | None,
) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s keyword arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

arguments : list[core_schema.ArgumentsParameter]

The core schema.

p_arguments_schema

def p_arguments_schema(
    arguments: list[core_schema.ArgumentsParameter],
    var_args_schema: CoreSchema | None,
) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function’s positional arguments.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

arguments : list[core_schema.ArgumentsParameter]

The core schema.

get_argument_name

def get_argument_name(argument: core_schema.ArgumentsParameter) -> str

Retrieves the name of an argument.

Returns

str — The name of the argument.

Parameters

argument : core_schema.ArgumentsParameter

The core schema.

call_schema

def call_schema(schema: core_schema.CallSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a function call.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.CallSchema

The core schema.

custom_error_schema

def custom_error_schema(schema: core_schema.CustomErrorSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a custom error.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.CustomErrorSchema

The core schema.

json_schema

def json_schema(schema: core_schema.JsonSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a JSON object.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.JsonSchema

The core schema.

url_schema

def url_schema(schema: core_schema.UrlSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a URL.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.UrlSchema

The core schema.

multi_host_url_schema

def multi_host_url_schema(schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.MultiHostUrlSchema

The core schema.

definitions_schema

def definitions_schema(schema: core_schema.DefinitionsSchema) -> JsonSchemaValue

Generates a JSON schema that matches a schema that defines a JSON object with definitions.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DefinitionsSchema

The core schema.

definition_ref_schema

def definition_ref_schema(
    schema: core_schema.DefinitionReferenceSchema,
) -> JsonSchemaValue

Generates a JSON schema that matches a schema that references a definition.

Returns

JsonSchemaValue — The generated JSON schema.

Parameters

schema : core_schema.DefinitionReferenceSchema

The core schema.

ser_schema

def ser_schema(
    schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema,
) -> JsonSchemaValue | None

Generates a JSON schema that matches a schema that defines a serialized object.

Returns

JsonSchemaValue | None — The generated JSON schema.

Parameters

schema : core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema

The core schema.

get_title_from_name

def get_title_from_name(name: str) -> str

Retrieves a title from a name.

Returns

str — The title.

Parameters

name : str

The name to retrieve a title from.

field_title_should_be_set

def field_title_should_be_set(schema: CoreSchemaOrField) -> bool

Returns true if a field with the given schema should have a title set based on the field name.

Intuitively, we want this to return true for schemas that wouldn’t otherwise provide their own title (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).

Returns

boolTrue if the field should have a title set, False otherwise.

Parameters

schema : CoreSchemaOrField

The schema to check.

normalize_name

def normalize_name(name: str) -> str

Normalizes a name to be used as a key in a dictionary.

Returns

str — The normalized name.

Parameters

name : str

The name to normalize.

get_defs_ref

def get_defs_ref(core_mode_ref: CoreModeRef) -> DefsRef

Override this method to change the way that definitions keys are generated from a core reference.

Returns

DefsRef — The definitions key.

Parameters

core_mode_ref : CoreModeRef

The core reference.

get_cache_defs_ref_schema

def get_cache_defs_ref_schema(core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]

This method wraps the get_defs_ref method with some cache-lookup/population logic, and returns both the produced defs_ref and the JSON schema that will refer to the right definition.

Returns

tuple[DefsRef, JsonSchemaValue] — A tuple of the definitions reference and the JSON schema that will refer to it.

Parameters

core_ref : CoreRef

The core reference to get the definitions reference for.

handle_ref_overrides

def handle_ref_overrides(json_schema: JsonSchemaValue) -> JsonSchemaValue

It is not valid for a schema with a top-level $ref to have sibling keys.

During our own schema generation, we treat sibling keys as overrides to the referenced schema, but this is not how the official JSON schema spec works.

Because of this, we first remove any sibling keys that are redundant with the referenced schema, then if any remain, we transform the schema from a top-level ‘$ref’ to use allOf to move the $ref out of the top level. (See bottom of https://swagger.io/docs/specification/using-ref/ for a reference about this behavior)

Returns

JsonSchemaValue

get_schema_from_definitions

def get_schema_from_definitions(json_ref: JsonRef) -> JsonSchemaValue | None
Returns

JsonSchemaValue | None

encode_default

def encode_default(dft: Any) -> Any

Encode a default value to a JSON-serializable value.

This is used to encode default values for fields in the generated JSON schema.

Returns

Any — The encoded default value.

Parameters

dft : Any

The default value to encode.

update_with_validations

def update_with_validations(
    json_schema: JsonSchemaValue,
    core_schema: CoreSchema,
    mapping: dict[str, str],
) -> None

Update the json_schema with the corresponding validations specified in the core_schema, using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.

Returns

None

Parameters

json_schema : JsonSchemaValue

The JSON schema to update.

core_schema : CoreSchema

The core schema to get the validations from.

mapping : dict[str, str]

A mapping from core_schema attribute names to the corresponding JSON schema attribute names.

get_flattened_anyof

def get_flattened_anyof(schemas: list[JsonSchemaValue]) -> JsonSchemaValue
Returns

JsonSchemaValue

get_json_ref_counts

def get_json_ref_counts(json_schema: JsonSchemaValue) -> dict[JsonRef, int]

Get all values corresponding to the key ‘$ref’ anywhere in the json_schema.

Returns

dict[JsonRef, int]

handle_invalid_for_json_schema

def handle_invalid_for_json_schema(
    schema: CoreSchemaOrField,
    error_info: str,
) -> JsonSchemaValue
Returns

JsonSchemaValue

emit_warning

def emit_warning(kind: JsonSchemaWarningKind, detail: str) -> None

This method simply emits PydanticJsonSchemaWarnings based on handling in the warning_message method.

Returns

None

render_warning_message

def render_warning_message(kind: JsonSchemaWarningKind, detail: str) -> str | None

This method is responsible for ignoring warnings as desired, and for formatting the warning messages.

You can override the value of ignored_warning_kinds in a subclass of GenerateJsonSchema to modify what warnings are generated. If you want more control, you can override this method; just return None in situations where you don’t want warnings to be emitted.

Returns

str | None — The formatted warning message, or None if no warning should be emitted.

Parameters

kind : JsonSchemaWarningKind

The kind of warning to render. It can be one of the following:

  • ‘skipped-choice’: A choice field was skipped because it had no valid choices.
  • ‘non-serializable-default’: A default value was skipped because it was not JSON-serializable.

detail : str

A string with additional details about the warning.


PydanticDeprecatedSince20

Bases: PydanticDeprecationWarning

A specific PydanticDeprecationWarning subclass defining functionality deprecated since Pydantic 2.0.


BaseModel

A base model class for creating Pydantic models.

Attributes

model_config

Type: ConfigDict Default: ConfigDict()

model_fields

Type: dict[str, FieldInfo]

model_computed_fields

Get the computed fields of this model instance.

Type: dict[str, ComputedFieldInfo]

model_extra

Get extra fields set during validation.

Type: dict[str, Any] | None

model_fields_set

Returns the set of fields that have been set on this model instance.

Type: set[str]

Methods

init

def __init__(__pydantic_self__, data: Any = {}) -> None

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

Uses __pydantic_self__ instead of the more common self for the first arg to allow self as a field name.

Returns

None

model_construct

@classmethod

def model_construct(
    cls: type[Model],
    _fields_set: set[str] | None = None,
    values: Any = {},
) -> Model

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = 'allow' was set since it adds all passed values

Returns

Model — A new instance of the Model class with validated data.

Parameters

_fields_set : set[str] | None Default: None

The set of field names accepted for the Model instance.

values : Any Default: \{\}

Trusted or pre-validated data dictionary.

model_copy

def model_copy(update: dict[str, Any] | None = None, deep: bool = False) -> Model

Returns a copy of the model.

Returns

Model — New model instance.

Parameters

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

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

deep : bool Default: False

Set to True to make a deep copy of the model.

model_dump

def model_dump(
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]

Usage docs: https://docs.pydantic.dev/dev-v2/usage/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Returns

dict[str, Any] — A dictionary representation of the model.

Parameters

mode : Literal['json', 'python'] | str Default: 'python'

The mode in which to_python should run. If mode is ‘json’, the dictionary will only contain JSON serializable types. If mode is ‘python’, the dictionary may contain any Python objects.

include : IncEx Default: None

A list of fields to include in the output.

exclude : IncEx Default: None

A list of fields to exclude from the output.

by_alias : bool Default: False

Whether to use the field’s alias in the dictionary key if defined.

exclude_unset : bool Default: False

Whether to exclude fields that are unset or None from the output.

exclude_defaults : bool Default: False

Whether to exclude fields that are set to their default value from the output.

exclude_none : bool Default: False

Whether to exclude fields that have a value of None from the output.

round_trip : bool Default: False

Whether to enable serialization and deserialization round-trip support.

warnings : bool Default: True

Whether to log warnings when invalid fields are encountered.

model_dump_json

def model_dump_json(
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str

Usage docs: https://docs.pydantic.dev/dev-v2/usage/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic’s to_json method.

Returns

str — A JSON string representation of the model.

Parameters

indent : int | None Default: None

Indentation to use in the JSON output. If None is passed, the output will be compact.

include : IncEx Default: None

Field(s) to include in the JSON output. Can take either a string or set of strings.

exclude : IncEx Default: None

Field(s) to exclude from the JSON output. Can take either a string or set of strings.

by_alias : bool Default: False

Whether to serialize using field aliases.

exclude_unset : bool Default: False

Whether to exclude fields that have not been explicitly set.

exclude_defaults : bool Default: False

Whether to exclude fields that have the default value.

exclude_none : bool Default: False

Whether to exclude fields that have a value of None.

round_trip : bool Default: False

Whether to use serialization/deserialization between JSON and class instance.

warnings : bool Default: True

Whether to show any warnings that occurred during serialization.

model_json_schema

@classmethod

def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]

Generates a JSON schema for a model class.

To override the logic used to generate the JSON schema, you can create a subclass of GenerateJsonSchema with your desired modifications, then override this method on a custom base class and set the default value of schema_generator to be your subclass.

Returns

dict[str, Any] — The JSON schema for the given model class.

Parameters

by_alias : bool Default: True

Whether to use attribute aliases or not.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The reference template.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

The JSON schema generator.

mode : JsonSchemaMode Default: 'validation'

The mode in which to generate the schema.

model_parametrized_name

@classmethod

def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Returns

str — String representing the new class where params are passed to cls as type variables.

Parameters

params : tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Raises
  • TypeError — Raised when trying to generate concrete names for non-generic models.

model_post_init

def model_post_init(__context: Any) -> None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Returns

None

model_rebuild

@classmethod

def model_rebuild(
    cls,
    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 model.

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.

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

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.

model_validate

@classmethod

def model_validate(
    cls: type[Model],
    obj: Any,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate a pydantic model instance.

Returns

Model — The validated model instance.

Parameters

obj : Any

The object to validate.

strict : bool | None Default: None

Whether to raise an exception on invalid fields.

from_attributes : bool | None Default: None

Whether to extract data from object attributes.

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

Additional context to pass to the validator.

Raises
  • ValidationError — If the object could not be validated.

model_validate_json

@classmethod

def model_validate_json(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given JSON data against the Pydantic model.

Returns

Model — The validated Pydantic model.

Parameters

json_data : str | bytes | bytearray

The JSON data to validate.

strict : bool | None Default: None

Whether to enforce types strictly.

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

Extra variables to pass to the validator.

Raises
  • ValueError — If json_data is not a JSON string.

get_pydantic_core_schema

@classmethod

def __get_pydantic_core_schema__(
    cls,
    __source: type[BaseModel],
    __handler: _annotated_handlers.GetCoreSchemaHandler,
) -> CoreSchema

Hook into generating the model’s CoreSchema.

Returns

CoreSchema — A pydantic-core CoreSchema.

Parameters

__source : type[BaseModel]

The class we are generating a schema for. This will generally be the same as the cls argument if this is a classmethod.

__handler : _annotated_handlers.GetCoreSchemaHandler

Call into Pydantic’s internal JSON schema generation. A callable that calls into Pydantic’s internal CoreSchema generation logic.

get_pydantic_json_schema

@classmethod

def __get_pydantic_json_schema__(
    cls,
    __core_schema: CoreSchema,
    __handler: _annotated_handlers.GetJsonSchemaHandler,
) -> JsonSchemaValue

Hook into generating the model’s JSON schema.

Returns

JsonSchemaValue — A JSON schema, as a Python object.

Parameters

__core_schema : CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema (\{'type': 'nullable', 'schema': current_schema\}), or just call the handler with the original schema.

__handler : _annotated_handlers.GetJsonSchemaHandler

Call into Pydantic’s internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

pydantic_init_subclass

@classmethod

def __pydantic_init_subclass__(cls, kwargs: Any = {}) -> None

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after the class is actually fully initialized. In particular, attributes like model_fields will be present when this is called.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren’t used internally by pydantic.

Returns

None

Parameters

**kwargs : Any Default: \{\}

Any keyword arguments passed to the class definition that aren’t used internally

copy

def __copy__() -> Model

Returns a shallow copy of the model.

Returns

Model

deepcopy

def __deepcopy__(memo: dict[int, Any] | None = None) -> Model

Returns a deep copy of the model.

Returns

Model

init_subclass

def __init_subclass__(cls, kwargs: Unpack[ConfigDict] = {})

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'):
    ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters

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

Keyword arguments passed to the class definition, which set model_config

iter

def __iter__() -> TupleGenerator

So dict(model) works.

Returns

TupleGenerator

dict

def dict(
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
) -> typing.Dict[str, Any]
Returns

typing.Dict[str, Any]

json

def json(
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    encoder: typing.Callable[[Any], Any] | None = PydanticUndefined,
    models_as_dict: bool = PydanticUndefined,
    dumps_kwargs: Any = {},
) -> str
Returns

str

parse_obj

@classmethod

def parse_obj(cls: type[Model], obj: Any) -> Model
Returns

Model

parse_raw

@classmethod

def parse_raw(
    cls: type[Model],
    b: str | bytes,
    content_type: str | None = None,
    encoding: str = 'utf8',
    proto: _deprecated_parse.Protocol | None = None,
    allow_pickle: bool = False,
) -> Model
Returns

Model

parse_file

@classmethod

def parse_file(
    cls: type[Model],
    path: str | Path,
    content_type: str | None = None,
    encoding: str = 'utf8',
    proto: _deprecated_parse.Protocol | None = None,
    allow_pickle: bool = False,
) -> Model
Returns

Model

from_orm

@classmethod

def from_orm(cls: type[Model], obj: Any) -> Model
Returns

Model

construct

@classmethod

def construct(
    cls: type[Model],
    _fields_set: set[str] | None = None,
    values: Any = {},
) -> Model
Returns

Model

copy

def copy(
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

This method is now deprecated; use model_copy instead. If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)
Returns

Model — A copy of the model with included, excluded and updated fields as specified.

Parameters

include : AbstractSetIntStr | MappingIntStrAny | None Default: None

Optional set or mapping specifying which fields to include in the copied model.

exclude : AbstractSetIntStr | MappingIntStrAny | None Default: None

Optional set or mapping specifying which fields to exclude in the copied model.

update : typing.Dict[str, Any] | None Default: None

Optional dictionary of field-value pairs to override field values in the copied model.

deep : bool Default: False

If True, the values of fields that are Pydantic models will be deep copied.

schema

@classmethod

def schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
) -> typing.Dict[str, Any]
Returns

typing.Dict[str, Any]

schema_json

@classmethod

def schema_json(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    dumps_kwargs: Any = {},
) -> str
Returns

str

validate

@classmethod

def validate(cls: type[Model], value: Any) -> Model
Returns

Model

update_forward_refs

@classmethod

def update_forward_refs(cls, localns: Any = {}) -> None
Returns

None


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.


model_json_schema

def model_json_schema(
    cls: type[BaseModel] | type[PydanticDataclass],
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]

Utility function to generate a JSON Schema for a model.

Returns

dict[str, Any] — The generated JSON Schema.

Parameters

cls : type[BaseModel] | type[PydanticDataclass]

The model class to generate a JSON Schema for.

by_alias : bool Default: True

If True (the default), fields will be serialized according to their alias. If False, fields will be serialized according to their attribute name.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The template to use for generating JSON Schema references.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

The class to use for generating the JSON Schema.

mode : JsonSchemaMode Default: 'validation'

The mode to use for generating the JSON Schema. It can be one of the following:

  • ‘validation’: Generate a JSON Schema for validating data.
  • ‘serialization’: Generate a JSON Schema for serializing data.

create_model

def create_model(
    __model_name: str,
    __config__: ConfigDict | None = None,
    __base__: None = None,
    __module__: str = __name__,
    __validators__: dict[str, AnyClassMethod] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    field_definitions: Any = {},
) -> type[BaseModel]
def create_model(
    __model_name: str,
    __config__: ConfigDict | None = None,
    __base__: type[Model] | tuple[type[Model], ...],
    __module__: str = __name__,
    __validators__: dict[str, AnyClassMethod] | None = None,
    __cls_kwargs__: dict[str, Any] | None = None,
    field_definitions: Any = {},
) -> type[Model]

Dynamically creates and returns a new Pydantic model.

Returns

type[Model] — The newly created model.

Parameters

__model_name : str

The name of the newly created model.

__config__ : ConfigDict | None Default: None

The configuration of the new model.

__base__ : type[Model] | tuple[type[Model], ...] | None Default: None

The base class for the new model.

__module__ : str Default: __name__

The name of the module that the model belongs to.

__validators__ : dict[str, AnyClassMethod] | None Default: None

A dictionary of methods that validate fields.

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

A dictionary of keyword arguments for class creation.

__slots__ : tuple[str, ...] | None Default: None

Deprecated. Should not be passed to create_model.

**field_definitions : Any Default: \{\}

Attributes of the new model. They should be passed in the format: <name>=(<type>, <default value>) or <name>=<default value>. For more complex cases, they can be passed in the format: <name>=<Field> or <name>=(<type>, <FieldInfo>).

Raises

  • PydanticUserError — If __base__ and __config__ are both passed.

DEFAULT_REF_TEMPLATE

The default format string used to generate reference names.

Default: '#/$defs/\{model\}'

JsonSchemaMode

A type alias that represents the mode of a JSON schema; either ‘validation’ or ‘serialization’.

For some types, the inputs to validation differ from the outputs of serialization. For example, computed fields will only be present when serializing, and should not be provided when validating. This flag provides a way to indicate whether you want the JSON schema required for validation inputs, or that will be matched by serialization outputs.

Default: Literal['validation', 'serialization']

JsonSchemaValue

A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary values.

Default: Dict[str, Any]

AbstractSetIntStr

Type: TypeAlias Default: 'typing.AbstractSet[int] | typing.AbstractSet[str]'

MappingIntStrAny

Type: TypeAlias Default: 'typing.Mapping[int, Any] | typing.Mapping[str, Any]'

AnyClassMethod

Default: classmethod[Any, Any, Any]

TupleGenerator

Default: typing.Generator[typing.Tuple[str, Any], None, None]

Model

Default: typing.TypeVar('Model', bound='BaseModel')

IncEx

Type: typing_extensions.TypeAlias Default: 'set[int] | set[str] | dict[int, Any] | dict[str, Any] | None'

DeprecationWarning

Default: PydanticDeprecatedSince20