pydantic_core.core_schema
This module contains definitions to build schemas which pydantic_core can
validate and serialize.
Bases: TypedDict
Base class for schema configuration options.
The name of the configuration.
Type: str
Whether the configuration should strictly adhere to specified rules.
Type: bool
The behavior for handling extra fields.
Type: ExtraBehavior
Whether the TypedDict should be considered total. Default is True.
Type: bool
Whether to use attributes for models, dataclasses, and tagged union keys.
Type: bool
Whether to use the used alias (or first alias for “field required” errors) instead of
field_names to construct error locs. Default is True.
Type: bool
Whether instances of models and dataclasses should re-validate. Default is ‘never’.
Type: Literal[‘always’, ‘never’, ‘subclass-instances’]
Whether to validate default values during validation. Default is False.
Type: bool
The maximum length for string fields.
Type: int
The minimum length for string fields.
Type: int
Whether to strip whitespace from string fields.
Type: bool
Whether to convert string fields to lowercase.
Type: bool
Whether to convert string fields to uppercase.
Type: bool
Whether to allow infinity and NaN values for float fields. Default is True.
Type: bool
The serialization option for timedelta values. Default is ‘iso8601’.
Note that if ser_json_temporal is set, then this param will be ignored.
Type: Literal[‘iso8601’, ‘float’]
The serialization option for datetime like values. Default is ‘iso8601’. The types this covers are datetime, date, time and timedelta. If this is set, it will take precedence over ser_json_timedelta
Type: Literal[‘iso8601’, ‘seconds’, ‘milliseconds’]
The serialization option for bytes values. Default is ‘utf8’.
Type: Literal[‘utf8’, ‘base64’, ‘hex’]
The serialization option for infinity and NaN values in float fields. Default is ‘null’.
Type: Literal[‘null’, ‘constants’, ‘strings’]
The validation option for bytes values, complementing ser_json_bytes. Default is ‘utf8’.
Type: Literal[‘utf8’, ‘base64’, ‘hex’]
Whether to hide input data from ValidationError representation.
Type: bool
Whether to add user-python excs to the cause of a ValidationError. Requires exceptiongroup backport pre Python 3.11.
Type: bool
Whether to enable coercion of any Number type to str (not applicable in strict mode).
Type: bool
The regex engine to use for regex pattern validation. Default is ‘rust-regex’. See StringSchema.
Type: Literal[‘rust-regex’, ‘python-re’]
Whether to cache strings. Default is True, True or 'all' is required to cache strings
during general validation since validators don’t know if they’re in a key or a value.
Type: Union[bool, Literal[‘all’, ‘keys’, ‘none’]]
Whether to use the field’s alias when validating against the provided input data. Default is True.
Type: bool
Whether to use the field’s name when validating against the provided input data. Default is False. Replacement for populate_by_name.
Type: bool
Whether to serialize by alias. Default is False, expected to change to True in V3.
Type: bool
Whether to preserve empty URL paths when validating values for a URL type. Defaults to False.
Type: bool
Bases: Protocol[ContextT]
Extra data used during serialization.
The include argument set during serialization.
Type: IncExCall
The exclude argument set during serialization.
Type: IncExCall
The current serialization context.
Type: ContextT
The serialization mode set during serialization.
Type: Literal[‘python’, ‘json’] | str
The by_alias argument set during serialization.
Type: bool
The exclude_unset argument set during serialization.
Type: bool
The exclude_defaults argument set during serialization.
Type: bool
The exclude_none argument set during serialization.
Type: bool
The exclude_computed_fields argument set during serialization.
Type: bool
The serialize_as_any argument set during serialization.
Type: bool
The round_trip argument set during serialization.
Type: bool
Bases: SerializationInfo[ContextT], Protocol
Extra data used during field serialization.
The name of the current field being serialized.
Type: str
Bases: Protocol[ContextT]
Extra data used during validation.
The current validation context.
Type: ContextT
The CoreConfig that applies to this validation.
Type: CoreConfig | None
The type of input data we are currently validating.
Type: Literal[‘python’, ‘json’]
The data being validated for this model.
The name of the current field being validated if this validator is attached to a model field.
def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema
Returns a schema for serialization with a custom type.
SimpleSerSchema
The type to use for serialization
def plain_serializer_function_ser_schema(
function: SerializerFunction,
is_field_serializer: bool | None = None,
info_arg: bool | None = None,
return_schema: CoreSchema | None = None,
when_used: WhenUsed = 'always',
) -> PlainSerializerFunctionSerSchema
Returns a schema for serialization with a function, can be either a “general” or “field” function.
PlainSerializerFunctionSerSchema
The function to use for serialization
Whether the serializer is for a field, e.g. takes model as the first argument,
and info includes field_name
Whether the function takes an info argument
return_schema : CoreSchema | None Default: None
Schema to use for serializing return value
When the function should be called
def wrap_serializer_function_ser_schema(
function: WrapSerializerFunction,
is_field_serializer: bool | None = None,
info_arg: bool | None = None,
schema: CoreSchema | None = None,
return_schema: CoreSchema | None = None,
when_used: WhenUsed = 'always',
) -> WrapSerializerFunctionSerSchema
Returns a schema for serialization with a wrap function, can be either a “general” or “field” function.
WrapSerializerFunctionSerSchema
The function to use for serialization
Whether the serializer is for a field, e.g. takes model as the first argument,
and info includes field_name
Whether the function takes an info argument
schema : CoreSchema | None Default: None
The schema to use for the inner serialization
return_schema : CoreSchema | None Default: None
Schema to use for serializing return value
When the function should be called
def format_ser_schema(
formatting_string: str,
when_used: WhenUsed = 'json-unless-none',
) -> FormatSerSchema
Returns a schema for serialization using python’s format method.
FormatSerSchema
formatting_string : str
String defining the format to use
Same meaning as for [general_function_plain_ser_schema], but with a different default
def to_string_ser_schema(when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema
Returns a schema for serialization using python’s str() / __str__ method.
ToStringSerSchema
Same meaning as for [general_function_plain_ser_schema], but with a different default
def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema
Returns a schema for serialization using a model.
ModelSerSchema
The expected class type, used to generate warnings if the wrong type is passed
Internal schema to use to serialize the model dict
def invalid_schema(
ref: str | None = None,
metadata: dict[str, Any] | None = None,
) -> InvalidSchema
Returns an invalid schema, used to indicate that a schema is invalid.
Returns a schema that matches any value, e.g.:
InvalidSchema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
def computed_field(
property_name: str,
return_schema: CoreSchema,
alias: str | None = None,
metadata: dict[str, Any] | None = None,
) -> ComputedField
ComputedFields are properties of a model or dataclass that are included in serialization.
ComputedField
property_name : str
The name of the property on the model or dataclass
The schema used for the type returned by the computed field
The name to use in the serialized output
Any other information you want to include with the schema, not used by pydantic-core
def any_schema(
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> AnySchema
Returns a schema that matches any value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.any_schema()
v = SchemaValidator(schema)
assert v.validate_python(1) == 1
AnySchema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def none_schema(
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> NoneSchema
Returns a schema that matches a None value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.none_schema()
v = SchemaValidator(schema)
assert v.validate_python(None) is None
NoneSchema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def bool_schema(
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> BoolSchema
Returns a schema that matches a bool value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.bool_schema()
v = SchemaValidator(schema)
assert v.validate_python('True') is True
BoolSchema
Whether the value should be a bool or a value that can be converted to a bool
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def int_schema(
multiple_of: int | None = None,
le: int | None = None,
ge: int | None = None,
lt: int | None = None,
gt: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> IntSchema
Returns a schema that matches a int value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.int_schema(multiple_of=2, le=6, ge=2)
v = SchemaValidator(schema)
assert v.validate_python('4') == 4
IntSchema
The value must be a multiple of this number
The value must be less than or equal to this number
The value must be greater than or equal to this number
The value must be strictly less than this number
The value must be strictly greater than this number
Whether the value should be a int or a value that can be converted to a int
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def float_schema(
allow_inf_nan: bool | None = None,
multiple_of: float | None = None,
le: float | None = None,
ge: float | None = None,
lt: float | None = None,
gt: float | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> FloatSchema
Returns a schema that matches a float value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.float_schema(le=0.8, ge=0.2)
v = SchemaValidator(schema)
assert v.validate_python('0.5') == 0.5
FloatSchema
Whether to allow inf and nan values
The value must be a multiple of this number
The value must be less than or equal to this number
The value must be greater than or equal to this number
The value must be strictly less than this number
The value must be strictly greater than this number
Whether the value should be a float or a value that can be converted to a float
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def decimal_schema(
allow_inf_nan: bool | None = None,
multiple_of: Decimal | None = None,
le: Decimal | None = None,
ge: Decimal | None = None,
lt: Decimal | None = None,
gt: Decimal | None = None,
max_digits: int | None = None,
decimal_places: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> DecimalSchema
Returns a schema that matches a decimal value, e.g.:
from decimal import Decimal
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.decimal_schema(le=0.8, ge=0.2)
v = SchemaValidator(schema)
assert v.validate_python('0.5') == Decimal('0.5')
DecimalSchema
Whether to allow inf and nan values
multiple_of : Decimal | None Default: None
The value must be a multiple of this number
le : Decimal | None Default: None
The value must be less than or equal to this number
ge : Decimal | None Default: None
The value must be greater than or equal to this number
lt : Decimal | None Default: None
The value must be strictly less than this number
gt : Decimal | None Default: None
The value must be strictly greater than this number
The maximum number of decimal digits allowed
The maximum number of decimal places allowed
Whether the value should be a float or a value that can be converted to a float
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def complex_schema(
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> ComplexSchema
Returns a schema that matches a complex value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.complex_schema()
v = SchemaValidator(schema)
assert v.validate_python('1+2j') == complex(1, 2)
assert v.validate_python(complex(1, 2)) == complex(1, 2)
ComplexSchema
Whether the value should be a complex object instance or a value that can be converted to a complex object
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def str_schema(
pattern: str | Pattern[str] | None = None,
max_length: int | None = None,
min_length: int | None = None,
strip_whitespace: bool | None = None,
to_lower: bool | None = None,
to_upper: bool | None = None,
regex_engine: Literal['rust-regex', 'python-re'] | None = None,
strict: bool | None = None,
coerce_numbers_to_str: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> StringSchema
Returns a schema that matches a string value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.str_schema(max_length=10, min_length=2)
v = SchemaValidator(schema)
assert v.validate_python('hello') == 'hello'
StringSchema
A regex pattern that the value must match
The value must be at most this length
The value must be at least this length
Whether to strip whitespace from the value
Whether to convert the value to lowercase
Whether to convert the value to uppercase
The regex engine to use for pattern validation. Default is ‘rust-regex’.
rust-regexuses theregexRust crate, which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.python-reuse theremodule, which supports all regex features, but may be slower.
Whether the value should be a string or a value that can be converted to a string
Whether to enable coercion of any Number type to str (not applicable in strict mode).
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def bytes_schema(
max_length: int | None = None,
min_length: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> BytesSchema
Returns a schema that matches a bytes value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.bytes_schema(max_length=10, min_length=2)
v = SchemaValidator(schema)
assert v.validate_python(b'hello') == b'hello'
BytesSchema
The value must be at most this length
The value must be at least this length
Whether the value should be a bytes or a value that can be converted to a bytes
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def date_schema(
strict: bool | None = None,
le: date | None = None,
ge: date | None = None,
lt: date | None = None,
gt: date | None = None,
now_op: Literal['past', 'future'] | None = None,
now_utc_offset: int | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> DateSchema
Returns a schema that matches a date value, e.g.:
from datetime import date
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
v = SchemaValidator(schema)
assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
DateSchema
Whether the value should be a date or a value that can be converted to a date
le : date | None Default: None
The value must be less than or equal to this date
ge : date | None Default: None
The value must be greater than or equal to this date
lt : date | None Default: None
The value must be strictly less than this date
gt : date | None Default: None
The value must be strictly greater than this date
The value must be in the past or future relative to the current date
The value must be in the past or future relative to the current date with this utc offset
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def time_schema(
strict: bool | None = None,
le: time | None = None,
ge: time | None = None,
lt: time | None = None,
gt: time | None = None,
tz_constraint: Literal['aware', 'naive'] | int | None = None,
microseconds_precision: Literal['truncate', 'error'] = 'truncate',
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> TimeSchema
Returns a schema that matches a time value, e.g.:
from datetime import time
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0))
v = SchemaValidator(schema)
assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0)
TimeSchema
Whether the value should be a time or a value that can be converted to a time
The value must be less than or equal to this time
The value must be greater than or equal to this time
The value must be strictly less than this time
The value must be strictly greater than this time
The value must be timezone aware or naive, or an int to indicate required tz offset
microseconds_precision : Literal[‘truncate’, ‘error’] Default: 'truncate'
The behavior when seconds have more than 6 digits or microseconds is too large
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def datetime_schema(
strict: bool | None = None,
le: datetime | None = None,
ge: datetime | None = None,
lt: datetime | None = None,
gt: datetime | None = None,
now_op: Literal['past', 'future'] | None = None,
tz_constraint: Literal['aware', 'naive'] | int | None = None,
now_utc_offset: int | None = None,
microseconds_precision: Literal['truncate', 'error'] = 'truncate',
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> DatetimeSchema
Returns a schema that matches a datetime value, e.g.:
from datetime import datetime
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.datetime_schema()
v = SchemaValidator(schema)
now = datetime.now()
assert v.validate_python(str(now)) == now
DatetimeSchema
Whether the value should be a datetime or a value that can be converted to a datetime
The value must be less than or equal to this datetime
The value must be greater than or equal to this datetime
The value must be strictly less than this datetime
The value must be strictly greater than this datetime
The value must be in the past or future relative to the current datetime
The value must be timezone aware or naive, or an int to indicate required tz offset TODO: use of a tzinfo where offset changes based on the datetime is not yet supported
The value must be in the past or future relative to the current datetime with this utc offset
microseconds_precision : Literal[‘truncate’, ‘error’] Default: 'truncate'
The behavior when seconds have more than 6 digits or microseconds is too large
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def timedelta_schema(
strict: bool | None = None,
le: timedelta | None = None,
ge: timedelta | None = None,
lt: timedelta | None = None,
gt: timedelta | None = None,
microseconds_precision: Literal['truncate', 'error'] = 'truncate',
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> TimedeltaSchema
Returns a schema that matches a timedelta value, e.g.:
from datetime import timedelta
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0))
v = SchemaValidator(schema)
assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12)
TimedeltaSchema
Whether the value should be a timedelta or a value that can be converted to a timedelta
le : timedelta | None Default: None
The value must be less than or equal to this timedelta
ge : timedelta | None Default: None
The value must be greater than or equal to this timedelta
lt : timedelta | None Default: None
The value must be strictly less than this timedelta
gt : timedelta | None Default: None
The value must be strictly greater than this timedelta
microseconds_precision : Literal[‘truncate’, ‘error’] Default: 'truncate'
The behavior when seconds have more than 6 digits or microseconds is too large
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def literal_schema(
expected: list[Any],
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> LiteralSchema
Returns a schema that matches a literal value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.literal_schema(['hello', 'world'])
v = SchemaValidator(schema)
assert v.validate_python('hello') == 'hello'
LiteralSchema
The value must be one of these values
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def enum_schema(
cls: Any,
members: list[Any],
sub_type: Literal['str', 'int', 'float'] | None = None,
missing: Callable[[Any], Any] | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> EnumSchema
Returns a schema that matches an enum value, e.g.:
from enum import Enum
from pydantic_core import SchemaValidator, core_schema
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
schema = core_schema.enum_schema(Color, list(Color.__members__.values()))
v = SchemaValidator(schema)
assert v.validate_python(2) is Color.GREEN
EnumSchema
cls : Any
The enum class
The members of the enum, generally list(MyEnum.__members__.values())
The type of the enum, either ‘str’ or ‘int’ or None for plain enums
A function to use when the value is not found in the enum, from _missing_
Whether to use strict mode, defaults to False
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def missing_sentinel_schema(
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> MissingSentinelSchema
Returns a schema for the MISSING sentinel.
MissingSentinelSchema
def is_instance_schema(
cls: Any,
cls_repr: str | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> IsInstanceSchema
Returns a schema that checks if a value is an instance of a class, equivalent to python’s isinstance method, e.g.:
from pydantic_core import SchemaValidator, core_schema
class A:
pass
schema = core_schema.is_instance_schema(cls=A)
v = SchemaValidator(schema)
v.validate_python(A())
IsInstanceSchema
cls : Any
The value must be an instance of this class
If provided this string is used in the validator name instead of repr(cls)
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def is_subclass_schema(
cls: type[Any],
cls_repr: str | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> IsInstanceSchema
Returns a schema that checks if a value is a subtype of a class, equivalent to python’s issubclass method, e.g.:
from pydantic_core import SchemaValidator, core_schema
class A:
pass
class B(A):
pass
schema = core_schema.is_subclass_schema(cls=A)
v = SchemaValidator(schema)
v.validate_python(B)
IsInstanceSchema
The value must be a subclass of this class
If provided this string is used in the validator name instead of repr(cls)
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def callable_schema(
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> CallableSchema
Returns a schema that checks if a value is callable, equivalent to python’s callable method, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.callable_schema()
v = SchemaValidator(schema)
v.validate_python(min)
CallableSchema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def list_schema(
items_schema: CoreSchema | None = None,
min_length: int | None = None,
max_length: int | None = None,
fail_fast: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: IncExSeqOrElseSerSchema | None = None,
) -> ListSchema
Returns a schema that matches a list value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10)
v = SchemaValidator(schema)
assert v.validate_python(['4']) == [4]
ListSchema
items_schema : CoreSchema | None Default: None
The value must be a list of items that match this schema
The value must be a list with at least this many items
The value must be a list with at most this many items
Stop validation on the first error
The value must be a list with exactly this many items
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : IncExSeqOrElseSerSchema | None Default: None
Custom serialization schema
def tuple_positional_schema(
items_schema: list[CoreSchema],
extras_schema: CoreSchema | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: IncExSeqOrElseSerSchema | None = None,
) -> TupleSchema
Returns a schema that matches a tuple of schemas, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.tuple_positional_schema(
[core_schema.int_schema(), core_schema.str_schema()]
)
v = SchemaValidator(schema)
assert v.validate_python((1, 'hello')) == (1, 'hello')
TupleSchema
items_schema : list[CoreSchema]
The value must be a tuple with items that match these schemas
extras_schema : CoreSchema | None Default: None
The value must be a tuple with items that match this schema
This was inspired by JSON schema’s prefixItems and items fields.
In python’s typing.Tuple, you can’t specify a type for “extra” items — they must all be the same type
if the length is variable. So this field won’t be set from a typing.Tuple annotation on a pydantic model.
The value must be a tuple with exactly this many items
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : IncExSeqOrElseSerSchema | None Default: None
Custom serialization schema
def tuple_variable_schema(
items_schema: CoreSchema | None = None,
min_length: int | None = None,
max_length: int | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: IncExSeqOrElseSerSchema | None = None,
) -> TupleSchema
Returns a schema that matches a tuple of a given schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.tuple_variable_schema(
items_schema=core_schema.int_schema(), min_length=0, max_length=10
)
v = SchemaValidator(schema)
assert v.validate_python(('1', 2, 3)) == (1, 2, 3)
TupleSchema
items_schema : CoreSchema | None Default: None
The value must be a tuple with items that match this schema
The value must be a tuple with at least this many items
The value must be a tuple with at most this many items
The value must be a tuple with exactly this many items
Optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : IncExSeqOrElseSerSchema | None Default: None
Custom serialization schema
def tuple_schema(
items_schema: list[CoreSchema],
variadic_item_index: int | None = None,
min_length: int | None = None,
max_length: int | None = None,
fail_fast: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: IncExSeqOrElseSerSchema | None = None,
) -> TupleSchema
Returns a schema that matches a tuple of schemas, with an optional variadic item, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.tuple_schema(
[core_schema.int_schema(), core_schema.str_schema(), core_schema.float_schema()],
variadic_item_index=1,
)
v = SchemaValidator(schema)
assert v.validate_python((1, 'hello', 'world', 1.5)) == (1, 'hello', 'world', 1.5)
TupleSchema
items_schema : list[CoreSchema]
The value must be a tuple with items that match these schemas
The index of the schema in items_schema to be treated as variadic (following PEP 646)
The value must be a tuple with at least this many items
The value must be a tuple with at most this many items
Stop validation on the first error
The value must be a tuple with exactly this many items
Optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : IncExSeqOrElseSerSchema | None Default: None
Custom serialization schema
def set_schema(
items_schema: CoreSchema | None = None,
min_length: int | None = None,
max_length: int | None = None,
fail_fast: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> SetSchema
Returns a schema that matches a set of a given schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.set_schema(
items_schema=core_schema.int_schema(), min_length=0, max_length=10
)
v = SchemaValidator(schema)
assert v.validate_python({1, '2', 3}) == {1, 2, 3}
SetSchema
items_schema : CoreSchema | None Default: None
The value must be a set with items that match this schema
The value must be a set with at least this many items
The value must be a set with at most this many items
Stop validation on the first error
The value must be a set with exactly this many items
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def frozenset_schema(
items_schema: CoreSchema | None = None,
min_length: int | None = None,
max_length: int | None = None,
fail_fast: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> FrozenSetSchema
Returns a schema that matches a frozenset of a given schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.frozenset_schema(
items_schema=core_schema.int_schema(), min_length=0, max_length=10
)
v = SchemaValidator(schema)
assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2})
FrozenSetSchema
items_schema : CoreSchema | None Default: None
The value must be a frozenset with items that match this schema
The value must be a frozenset with at least this many items
The value must be a frozenset with at most this many items
Stop validation on the first error
The value must be a frozenset with exactly this many items
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def generator_schema(
items_schema: CoreSchema | None = None,
min_length: int | None = None,
max_length: int | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: IncExSeqOrElseSerSchema | None = None,
) -> GeneratorSchema
Returns a schema that matches a generator value, e.g.:
from typing import Iterator
from pydantic_core import SchemaValidator, core_schema
def gen() -> Iterator[int]:
yield 1
schema = core_schema.generator_schema(items_schema=core_schema.int_schema())
v = SchemaValidator(schema)
v.validate_python(gen())
Unlike other types, validated generators do not raise ValidationErrors eagerly, but instead will raise a ValidationError when a violating value is actually read from the generator. This is to ensure that “validated” generators retain the benefit of lazy evaluation.
GeneratorSchema
items_schema : CoreSchema | None Default: None
The value must be a generator with items that match this schema
The value must be a generator that yields at least this many items
The value must be a generator that yields at most this many items
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : IncExSeqOrElseSerSchema | None Default: None
Custom serialization schema
def dict_schema(
keys_schema: CoreSchema | None = None,
values_schema: CoreSchema | None = None,
min_length: int | None = None,
max_length: int | None = None,
fail_fast: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> DictSchema
Returns a schema that matches a dict value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.dict_schema(
keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
)
v = SchemaValidator(schema)
assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2}
DictSchema
keys_schema : CoreSchema | None Default: None
The value must be a dict with keys that match this schema
values_schema : CoreSchema | None Default: None
The value must be a dict with values that match this schema
The value must be a dict with at least this many items
The value must be a dict with at most this many items
Stop validation on the first error
Whether the keys and values should be validated with strict mode
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def no_info_before_validator_function(
function: NoInfoValidatorFunction,
schema: CoreSchema,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> BeforeValidatorFunctionSchema
Returns a schema that calls a validator function before validating, no info argument is provided, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: bytes) -> str:
return v.decode() + 'world'
func_schema = core_schema.no_info_before_validator_function(
function=fn, schema=core_schema.str_schema()
)
schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
v = SchemaValidator(schema)
assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
BeforeValidatorFunctionSchema
The validator function to call
The schema to validate the output of the validator function
optional unique identifier of the schema, used to reference the schema in other places
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def with_info_before_validator_function(
function: WithInfoValidatorFunction,
schema: CoreSchema,
field_name: str | None = None,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> BeforeValidatorFunctionSchema
Returns a schema that calls a validator function before validation, the function is called with
an info argument, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: bytes, info: core_schema.ValidationInfo) -> str:
assert info.data is not None
assert info.field_name is not None
return v.decode() + 'world'
func_schema = core_schema.with_info_before_validator_function(
function=fn, schema=core_schema.str_schema()
)
schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
v = SchemaValidator(schema)
assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
BeforeValidatorFunctionSchema
The validator function to call
The name of the field this validator is applied to, if any (deprecated)
The schema to validate the output of the validator function
optional unique identifier of the schema, used to reference the schema in other places
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def no_info_after_validator_function(
function: NoInfoValidatorFunction,
schema: CoreSchema,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> AfterValidatorFunctionSchema
Returns a schema that calls a validator function after validating, no info argument is provided, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: str) -> str:
return v + 'world'
func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema())
schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
v = SchemaValidator(schema)
assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
AfterValidatorFunctionSchema
The validator function to call after the schema is validated
The schema to validate before the validator function
optional unique identifier of the schema, used to reference the schema in other places
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def with_info_after_validator_function(
function: WithInfoValidatorFunction,
schema: CoreSchema,
field_name: str | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> AfterValidatorFunctionSchema
Returns a schema that calls a validator function after validation, the function is called with
an info argument, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: str, info: core_schema.ValidationInfo) -> str:
assert info.data is not None
assert info.field_name is not None
return v + 'world'
func_schema = core_schema.with_info_after_validator_function(
function=fn, schema=core_schema.str_schema()
)
schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
v = SchemaValidator(schema)
assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
AfterValidatorFunctionSchema
The validator function to call after the schema is validated
The schema to validate before the validator function
The name of the field this validator is applied to, if any (deprecated)
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def no_info_wrap_validator_function(
function: NoInfoWrapValidatorFunction,
schema: CoreSchema,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> WrapValidatorFunctionSchema
Returns a schema which calls a function with a validator callable argument which can
optionally be used to call inner validation with the function logic, this is much like the
“onion” implementation of middleware in many popular web frameworks, no info argument is passed, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(
v: str,
validator: core_schema.ValidatorFunctionWrapHandler,
) -> str:
return validator(input_value=v) + 'world'
schema = core_schema.no_info_wrap_validator_function(
function=fn, schema=core_schema.str_schema()
)
v = SchemaValidator(schema)
assert v.validate_python('hello ') == 'hello world'
WrapValidatorFunctionSchema
The validator function to call
The schema to validate the output of the validator function
optional unique identifier of the schema, used to reference the schema in other places
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def with_info_wrap_validator_function(
function: WithInfoWrapValidatorFunction,
schema: CoreSchema,
field_name: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> WrapValidatorFunctionSchema
Returns a schema which calls a function with a validator callable argument which can
optionally be used to call inner validation with the function logic, this is much like the
“onion” implementation of middleware in many popular web frameworks, an info argument is also passed, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(
v: str,
validator: core_schema.ValidatorFunctionWrapHandler,
info: core_schema.ValidationInfo,
) -> str:
return validator(input_value=v) + 'world'
schema = core_schema.with_info_wrap_validator_function(
function=fn, schema=core_schema.str_schema()
)
v = SchemaValidator(schema)
assert v.validate_python('hello ') == 'hello world'
WrapValidatorFunctionSchema
The validator function to call
The schema to validate the output of the validator function
The name of the field this validator is applied to, if any (deprecated)
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def no_info_plain_validator_function(
function: NoInfoValidatorFunction,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> PlainValidatorFunctionSchema
Returns a schema that uses the provided function for validation, no info argument is passed, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: str) -> str:
assert 'hello' in v
return v + 'world'
schema = core_schema.no_info_plain_validator_function(function=fn)
v = SchemaValidator(schema)
assert v.validate_python('hello ') == 'hello world'
PlainValidatorFunctionSchema
The validator function to call
optional unique identifier of the schema, used to reference the schema in other places
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def with_info_plain_validator_function(
function: WithInfoValidatorFunction,
field_name: str | None = None,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> PlainValidatorFunctionSchema
Returns a schema that uses the provided function for validation, an info argument is passed, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: str, info: core_schema.ValidationInfo) -> str:
assert 'hello' in v
return v + 'world'
schema = core_schema.with_info_plain_validator_function(function=fn)
v = SchemaValidator(schema)
assert v.validate_python('hello ') == 'hello world'
PlainValidatorFunctionSchema
The validator function to call
The name of the field this validator is applied to, if any (deprecated)
optional unique identifier of the schema, used to reference the schema in other places
json_schema_input_schema : CoreSchema | None Default: None
The core schema to be used to generate the corresponding JSON Schema input type
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def with_default_schema(
schema: CoreSchema,
default: Any = PydanticUndefined,
default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any], None] = None,
default_factory_takes_data: bool | None = None,
on_error: Literal['raise', 'omit', 'default'] | None = None,
validate_default: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> WithDefaultSchema
Returns a schema that adds a default value to the given schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello')
wrapper_schema = core_schema.typed_dict_schema(
{'a': core_schema.typed_dict_field(schema)}
)
v = SchemaValidator(wrapper_schema)
assert v.validate_python({}) == v.validate_python({'a': 'hello'})
WithDefaultSchema
The schema to add a default value to
default : Any Default: PydanticUndefined
The default value to use
A callable that returns the default value to use
Whether the default factory takes a validated data argument
What to do if the schema validation fails. One of ‘raise’, ‘omit’, ‘default’
Whether the default value should be validated
Whether the underlying schema should be validated with strict mode
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def nullable_schema(
schema: CoreSchema,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> NullableSchema
Returns a schema that matches a nullable value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.nullable_schema(core_schema.str_schema())
v = SchemaValidator(schema)
assert v.validate_python(None) is None
NullableSchema
The schema to wrap
Whether the underlying schema should be validated with strict mode
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def union_schema(
choices: list[CoreSchema | tuple[CoreSchema, str]],
auto_collapse: bool | None = None,
custom_error_type: str | None = None,
custom_error_message: str | None = None,
custom_error_context: dict[str, str | int] | None = None,
mode: Literal['smart', 'left_to_right'] | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> UnionSchema
Returns a schema that matches a union value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()])
v = SchemaValidator(schema)
assert v.validate_python('hello') == 'hello'
assert v.validate_python(1) == 1
UnionSchema
The schemas to match. If a tuple, the second item is used as the label for the case.
whether to automatically collapse unions with one element to the inner validator, default true
The custom error type to use if the validation fails
The custom error message to use if the validation fails
The custom error context to use if the validation fails
How to select which choice to return
smart(default) will try to return the choice which is the closest match to the input valueleft_to_rightwill return the first choice inchoiceswhich succeeds validation
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def tagged_union_schema(
choices: dict[Any, CoreSchema],
discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], Any],
custom_error_type: str | None = None,
custom_error_message: str | None = None,
custom_error_context: dict[str, int | str | float] | None = None,
strict: bool | None = None,
from_attributes: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> TaggedUnionSchema
Returns a schema that matches a tagged union value, e.g.:
from pydantic_core import SchemaValidator, core_schema
apple_schema = core_schema.typed_dict_schema(
{
'foo': core_schema.typed_dict_field(core_schema.str_schema()),
'bar': core_schema.typed_dict_field(core_schema.int_schema()),
}
)
banana_schema = core_schema.typed_dict_schema(
{
'foo': core_schema.typed_dict_field(core_schema.str_schema()),
'spam': core_schema.typed_dict_field(
core_schema.list_schema(items_schema=core_schema.int_schema())
),
}
)
schema = core_schema.tagged_union_schema(
choices={
'apple': apple_schema,
'banana': banana_schema,
},
discriminator='foo',
)
v = SchemaValidator(schema)
assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123}
assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == {
'foo': 'banana',
'spam': [1, 2, 3],
}
TaggedUnionSchema
The schemas to match
When retrieving a schema from choices using the discriminator value, if the value is a str,
it should be fed back into the choices map until a schema is obtained
(This approach is to prevent multiple ownership of a single schema in Rust)
The discriminator to use to determine the schema to use
- If
discriminatoris a str, it is the name of the attribute to use as the discriminator - If
discriminatoris a list of int/str, it should be used as a “path” to access the discriminator - If
discriminatoris a list of lists, each inner list is a path, and the first path that exists is used - If
discriminatoris a callable, it should return the discriminator when called on the value to validate; the callable can returnNoneto indicate that there is no matching discriminator present on the input
The custom error type to use if the validation fails
The custom error message to use if the validation fails
The custom error context to use if the validation fails
Whether the underlying schemas should be validated with strict mode
Whether to use the attributes of the object to retrieve the discriminator value
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def chain_schema(
steps: list[CoreSchema],
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> ChainSchema
Returns a schema that chains the provided validation schemas, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: str, info: core_schema.ValidationInfo) -> str:
assert 'hello' in v
return v + ' world'
fn_schema = core_schema.with_info_plain_validator_function(function=fn)
schema = core_schema.chain_schema(
[fn_schema, fn_schema, fn_schema, core_schema.str_schema()]
)
v = SchemaValidator(schema)
assert v.validate_python('hello') == 'hello world world world'
ChainSchema
steps : list[CoreSchema]
The schemas to chain
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def lax_or_strict_schema(
lax_schema: CoreSchema,
strict_schema: CoreSchema,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> LaxOrStrictSchema
Returns a schema that uses the lax or strict schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
def fn(v: str, info: core_schema.ValidationInfo) -> str:
assert 'hello' in v
return v + ' world'
lax_schema = core_schema.int_schema(strict=False)
strict_schema = core_schema.int_schema(strict=True)
schema = core_schema.lax_or_strict_schema(
lax_schema=lax_schema, strict_schema=strict_schema, strict=True
)
v = SchemaValidator(schema)
assert v.validate_python(123) == 123
schema = core_schema.lax_or_strict_schema(
lax_schema=lax_schema, strict_schema=strict_schema, strict=False
)
v = SchemaValidator(schema)
assert v.validate_python('123') == 123
LaxOrStrictSchema
The lax schema to use
The strict schema to use
Whether the strict schema should be used
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def json_or_python_schema(
json_schema: CoreSchema,
python_schema: CoreSchema,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> JsonOrPythonSchema
Returns a schema that uses the Json or Python schema depending on the input:
from pydantic_core import SchemaValidator, ValidationError, core_schema
v = SchemaValidator(
core_schema.json_or_python_schema(
json_schema=core_schema.int_schema(),
python_schema=core_schema.int_schema(strict=True),
)
)
assert v.validate_json('"123"') == 123
try:
v.validate_python('123')
except ValidationError:
pass
else:
raise AssertionError('Validation should have failed')
JsonOrPythonSchema
The schema to use for Json inputs
The schema to use for Python inputs
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def typed_dict_field(
schema: CoreSchema,
required: bool | None = None,
validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
serialization_alias: str | None = None,
serialization_exclude: bool | None = None,
metadata: dict[str, Any] | None = None,
serialization_exclude_if: Callable[[Any], bool] | None = None,
) -> TypedDictField
Returns a schema that matches a typed dict field, e.g.:
from pydantic_core import core_schema
field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True)
TypedDictField
The schema to use for the field
Whether the field is required, otherwise uses the value from total on the typed dict
The alias(es) to use to find the field in the validation data
The alias to use as a key when serializing
Whether to exclude the field when serializing
A callable that determines whether to exclude the field when serializing based on its value.
Any other information you want to include with the schema, not used by pydantic-core
def typed_dict_schema(
fields: dict[str, TypedDictField],
cls: type[Any] | None = None,
cls_name: str | None = None,
computed_fields: list[ComputedField] | None = None,
strict: bool | None = None,
extras_schema: CoreSchema | None = None,
extra_behavior: ExtraBehavior | None = None,
total: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
config: CoreConfig | None = None,
) -> TypedDictSchema
Returns a schema that matches a typed dict, e.g.:
from typing_extensions import TypedDict
from pydantic_core import SchemaValidator, core_schema
class MyTypedDict(TypedDict):
a: str
wrapper_schema = core_schema.typed_dict_schema(
{'a': core_schema.typed_dict_field(core_schema.str_schema())}, cls=MyTypedDict
)
v = SchemaValidator(wrapper_schema)
assert v.validate_python({'a': 'hello'}) == {'a': 'hello'}
TypedDictSchema
The fields to use for the typed dict
The class to use for the typed dict
The name to use in error locations. Falls back to cls.__name__, or the validator name if no class
is provided.
Computed fields to use when serializing the model, only applies when directly inside a model
Whether the typed dict is strict
extras_schema : CoreSchema | None Default: None
The extra validator to use for the typed dict
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
extra_behavior : ExtraBehavior | None Default: None
The extra behavior to use for the typed dict
Whether the typed dict is total, otherwise uses typed_dict_total from config
serialization : SerSchema | None Default: None
Custom serialization schema
def model_field(
schema: CoreSchema,
validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
serialization_alias: str | None = None,
serialization_exclude: bool | None = None,
serialization_exclude_if: Callable[[Any], bool] | None = None,
frozen: bool | None = None,
metadata: dict[str, Any] | None = None,
) -> ModelField
Returns a schema for a model field, e.g.:
from pydantic_core import core_schema
field = core_schema.model_field(schema=core_schema.int_schema())
ModelField
The schema to use for the field
The alias(es) to use to find the field in the validation data
The alias to use as a key when serializing
Whether to exclude the field when serializing
A Callable that determines whether to exclude a field during serialization based on its value.
Whether the field is frozen
Any other information you want to include with the schema, not used by pydantic-core
def model_fields_schema(
fields: dict[str, ModelField],
model_name: str | None = None,
computed_fields: list[ComputedField] | None = None,
strict: bool | None = None,
extras_schema: CoreSchema | None = None,
extras_keys_schema: CoreSchema | None = None,
extra_behavior: ExtraBehavior | None = None,
from_attributes: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> ModelFieldsSchema
Returns a schema that matches the fields of a Pydantic model, e.g.:
from pydantic_core import SchemaValidator, core_schema
wrapper_schema = core_schema.model_fields_schema(
{'a': core_schema.model_field(core_schema.str_schema())}
)
v = SchemaValidator(wrapper_schema)
print(v.validate_python({'a': 'hello'}))
#> ({'a': 'hello'}, None, {'a'})
ModelFieldsSchema
The fields of the model
The name of the model, used for error messages, defaults to “Model”
Computed fields to use when serializing the model, only applies when directly inside a model
Whether the model is strict
extras_schema : CoreSchema | None Default: None
The schema to use when validating extra input data
extras_keys_schema : CoreSchema | None Default: None
The schema to use when validating the keys of extra input data
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
extra_behavior : ExtraBehavior | None Default: None
The extra behavior to use for the model fields
Whether the model fields should be populated from attributes
serialization : SerSchema | None Default: None
Custom serialization schema
def model_schema(
cls: type[Any],
schema: CoreSchema,
generic_origin: type[Any] | None = None,
custom_init: bool | None = None,
root_model: bool | None = None,
post_init: str | None = None,
revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
strict: bool | None = None,
frozen: bool | None = None,
extra_behavior: ExtraBehavior | None = None,
config: CoreConfig | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> ModelSchema
A model schema generally contains a typed-dict schema.
It will run the typed dict validator, then create a new class
and set the dict and fields set returned from the typed dict validator
to __dict__ and __pydantic_fields_set__ respectively.
Example:
from pydantic_core import CoreConfig, SchemaValidator, core_schema
class MyModel:
__slots__ = (
'__dict__',
'__pydantic_fields_set__',
'__pydantic_extra__',
'__pydantic_private__',
)
schema = core_schema.model_schema(
cls=MyModel,
config=CoreConfig(str_max_length=5),
schema=core_schema.model_fields_schema(
fields={'a': core_schema.model_field(core_schema.str_schema())},
),
)
v = SchemaValidator(schema)
assert v.isinstance_python({'a': 'hello'}) is True
assert v.isinstance_python({'a': 'too long'}) is False
ModelSchema
The class to use for the model
The schema to use for the model
The origin type used for this model, if it’s a parametrized generic. Ex,
if this model schema represents SomeModel[int], generic_origin is SomeModel
Whether the model has a custom init method
Whether the model is a RootModel
The call after init to use for the model
whether instances of models and dataclasses (including subclass instances) should re-validate defaults to config.revalidate_instances, else ‘never’
Whether the model is strict
Whether the model is frozen
extra_behavior : ExtraBehavior | None Default: None
The extra behavior to use for the model, used in serialization
config : CoreConfig | None Default: None
The config to use for the model
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def dataclass_field(
name: str,
schema: CoreSchema,
kw_only: bool | None = None,
init: bool | None = None,
init_only: bool | None = None,
validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
serialization_alias: str | None = None,
serialization_exclude: bool | None = None,
metadata: dict[str, Any] | None = None,
serialization_exclude_if: Callable[[Any], bool] | None = None,
frozen: bool | None = None,
) -> DataclassField
Returns a schema for a dataclass field, e.g.:
from pydantic_core import SchemaValidator, core_schema
field = core_schema.dataclass_field(
name='a', schema=core_schema.str_schema(), kw_only=False
)
schema = core_schema.dataclass_args_schema('Foobar', [field])
v = SchemaValidator(schema)
assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None)
DataclassField
name : str
The name to use for the argument parameter
The schema to use for the argument parameter
Whether the field can be set with a positional argument as well as a keyword argument
Whether the field should be validated during initialization
Whether the field should be omitted from __dict__ and passed to __post_init__
The alias(es) to use to find the field in the validation data
The alias to use as a key when serializing
Whether to exclude the field when serializing
A callable that determines whether to exclude the field when serializing based on its value.
Any other information you want to include with the schema, not used by pydantic-core
Whether the field is frozen
def dataclass_args_schema(
dataclass_name: str,
fields: list[DataclassField],
computed_fields: list[ComputedField] | None = None,
collect_init_only: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
extra_behavior: ExtraBehavior | None = None,
) -> DataclassArgsSchema
Returns a schema for validating dataclass arguments, e.g.:
from pydantic_core import SchemaValidator, core_schema
field_a = core_schema.dataclass_field(
name='a', schema=core_schema.str_schema(), kw_only=False
)
field_b = core_schema.dataclass_field(
name='b', schema=core_schema.bool_schema(), kw_only=False
)
schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b])
v = SchemaValidator(schema)
assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None)
DataclassArgsSchema
dataclass_name : str
The name of the dataclass being validated
fields : list[DataclassField]
The fields to use for the dataclass
Computed fields to use when serializing the dataclass
Whether to collect init only fields into a dict to pass to __post_init__
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
extra_behavior : ExtraBehavior | None Default: None
How to handle extra fields
def dataclass_schema(
cls: type[Any],
schema: CoreSchema,
fields: list[str],
generic_origin: type[Any] | None = None,
cls_name: str | None = None,
post_init: bool | None = None,
revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
frozen: bool | None = None,
slots: bool | None = None,
config: CoreConfig | None = None,
) -> DataclassSchema
Returns a schema for a dataclass. As with ModelSchema, this schema can only be used as a field within
another schema, not as the root type.
DataclassSchema
The dataclass type, used to perform subclass checks
The schema to use for the dataclass fields
Fields of the dataclass, this is used in serialization and in validation during re-validation and while validating assignment
The origin type used for this dataclass, if it’s a parametrized generic. Ex,
if this model schema represents SomeDataclass[int], generic_origin is SomeDataclass
The name to use in error locs, etc; this is useful for generics (default: cls.__name__)
Whether to call __post_init__ after validation
whether instances of models and dataclasses (including subclass instances) should re-validate defaults to config.revalidate_instances, else ‘never’
Whether to require an exact instance of cls
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
Whether the dataclass is frozen
Whether slots=True on the dataclass, means each field is assigned independently, rather than
simply setting __dict__, default false
def arguments_parameter(
name: str,
schema: CoreSchema,
mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None,
alias: str | list[str | int] | list[list[str | int]] | None = None,
) -> ArgumentsParameter
Returns a schema that matches an argument parameter, e.g.:
from pydantic_core import SchemaValidator, core_schema
param = core_schema.arguments_parameter(
name='a', schema=core_schema.str_schema(), mode='positional_only'
)
schema = core_schema.arguments_schema([param])
v = SchemaValidator(schema)
assert v.validate_python(('hello',)) == (('hello',), {})
ArgumentsParameter
name : str
The name to use for the argument parameter
The schema to use for the argument parameter
The mode to use for the argument parameter
The alias to use for the argument parameter
def arguments_schema(
arguments: list[ArgumentsParameter],
validate_by_name: bool | None = None,
validate_by_alias: bool | None = None,
var_args_schema: CoreSchema | None = None,
var_kwargs_mode: VarKwargsMode | None = None,
var_kwargs_schema: CoreSchema | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> ArgumentsSchema
Returns a schema that matches an arguments schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
param_a = core_schema.arguments_parameter(
name='a', schema=core_schema.str_schema(), mode='positional_only'
)
param_b = core_schema.arguments_parameter(
name='b', schema=core_schema.bool_schema(), mode='positional_only'
)
schema = core_schema.arguments_schema([param_a, param_b])
v = SchemaValidator(schema)
assert v.validate_python(('hello', True)) == (('hello', True), {})
ArgumentsSchema
arguments : list[ArgumentsParameter]
The arguments to use for the arguments schema
Whether to populate by the parameter names, defaults to False.
Whether to populate by the parameter aliases, defaults to True.
var_args_schema : CoreSchema | None Default: None
The variable args schema to use for the arguments schema
var_kwargs_mode : VarKwargsMode | None Default: None
The validation mode to use for variadic keyword arguments. If 'uniform', every value of the
keyword arguments will be validated against the var_kwargs_schema schema. If 'unpacked-typed-dict',
the var_kwargs_schema argument must be a typed_dict_schema
var_kwargs_schema : CoreSchema | None Default: None
The variable kwargs schema to use for the arguments schema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def arguments_v3_parameter(
name: str,
schema: CoreSchema,
mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only', 'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict'] | None = None,
alias: str | list[str | int] | list[list[str | int]] | None = None,
) -> ArgumentsV3Parameter
Returns a schema that matches an argument parameter, e.g.:
from pydantic_core import SchemaValidator, core_schema
param = core_schema.arguments_v3_parameter(
name='a', schema=core_schema.str_schema(), mode='positional_only'
)
schema = core_schema.arguments_v3_schema([param])
v = SchemaValidator(schema)
assert v.validate_python({'a': 'hello'}) == (('hello',), {})
ArgumentsV3Parameter
name : str
The name to use for the argument parameter
The schema to use for the argument parameter
mode : Literal[‘positional_only’, ‘positional_or_keyword’, ‘keyword_only’, ‘var_args’, ‘var_kwargs_uniform’, ‘var_kwargs_unpacked_typed_dict’] | None Default: None
The mode to use for the argument parameter
The alias to use for the argument parameter
def arguments_v3_schema(
arguments: list[ArgumentsV3Parameter],
validate_by_name: bool | None = None,
validate_by_alias: bool | None = None,
extra_behavior: Literal['forbid', 'ignore'] | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> ArgumentsV3Schema
Returns a schema that matches an arguments schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
param_a = core_schema.arguments_v3_parameter(
name='a', schema=core_schema.str_schema(), mode='positional_only'
)
param_b = core_schema.arguments_v3_parameter(
name='kwargs', schema=core_schema.bool_schema(), mode='var_kwargs_uniform'
)
schema = core_schema.arguments_v3_schema([param_a, param_b])
v = SchemaValidator(schema)
assert v.validate_python({'a': 'hi', 'kwargs': {'b': True}}) == (('hi',), {'b': True})
This schema is currently not used by other Pydantic components. In V3, it will most likely
become the default arguments schema for the 'call' schema.
ArgumentsV3Schema
arguments : list[ArgumentsV3Parameter]
The arguments to use for the arguments schema.
Whether to populate by the parameter names, defaults to False.
Whether to populate by the parameter aliases, defaults to True.
The extra behavior to use.
optional unique identifier of the schema, used to reference the schema in other places.
Any other information you want to include with the schema, not used by pydantic-core.
serialization : SerSchema | None Default: None
Custom serialization schema.
def call_schema(
arguments: CoreSchema,
function: Callable[..., Any],
function_name: str | None = None,
return_schema: CoreSchema | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> CallSchema
Returns a schema that matches an arguments schema, then calls a function, e.g.:
from pydantic_core import SchemaValidator, core_schema
param_a = core_schema.arguments_parameter(
name='a', schema=core_schema.str_schema(), mode='positional_only'
)
param_b = core_schema.arguments_parameter(
name='b', schema=core_schema.bool_schema(), mode='positional_only'
)
args_schema = core_schema.arguments_schema([param_a, param_b])
schema = core_schema.call_schema(
arguments=args_schema,
function=lambda a, b: a + str(not b),
return_schema=core_schema.str_schema(),
)
v = SchemaValidator(schema)
assert v.validate_python((('hello', True))) == 'helloFalse'
CallSchema
The arguments to use for the arguments schema
The function to use for the call schema
The function name to use for the call schema, if not provided function.__name__ is used
return_schema : CoreSchema | None Default: None
The return schema to use for the call schema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def custom_error_schema(
schema: CoreSchema,
custom_error_type: str,
custom_error_message: str | None = None,
custom_error_context: dict[str, Any] | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> CustomErrorSchema
Returns a schema that matches a custom error value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.custom_error_schema(
schema=core_schema.int_schema(),
custom_error_type='MyError',
custom_error_message='Error msg',
)
v = SchemaValidator(schema)
v.validate_python(1)
CustomErrorSchema
The schema to use for the custom error schema
custom_error_type : str
The custom error type to use for the custom error schema
The custom error message to use for the custom error schema
The custom error context to use for the custom error schema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def json_schema(
schema: CoreSchema | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> JsonSchema
Returns a schema that matches a JSON value, e.g.:
from pydantic_core import SchemaValidator, core_schema
dict_schema = core_schema.model_fields_schema(
{
'field_a': core_schema.model_field(core_schema.str_schema()),
'field_b': core_schema.model_field(core_schema.bool_schema()),
},
)
class MyModel:
__slots__ = (
'__dict__',
'__pydantic_fields_set__',
'__pydantic_extra__',
'__pydantic_private__',
)
field_a: str
field_b: bool
json_schema = core_schema.json_schema(schema=dict_schema)
schema = core_schema.model_schema(cls=MyModel, schema=json_schema)
v = SchemaValidator(schema)
m = v.validate_python('{"field_a": "hello", "field_b": true}')
assert isinstance(m, MyModel)
JsonSchema
schema : CoreSchema | None Default: None
The schema to use for the JSON schema
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def url_schema(
max_length: int | None = None,
allowed_schemes: list[str] | None = None,
host_required: bool | None = None,
default_host: str | None = None,
default_port: int | None = None,
default_path: str | None = None,
preserve_empty_path: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> UrlSchema
Returns a schema that matches a URL value, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.url_schema()
v = SchemaValidator(schema)
print(v.validate_python('https://example.com'))
#> https://example.com/
UrlSchema
The maximum length of the URL
The allowed URL schemes
Whether the URL must have a host
The default host to use if the URL does not have a host
The default port to use if the URL does not have a port
The default path to use if the URL does not have a path
Whether to preserve an empty path or convert it to ’/’, default False
Whether to use strict URL parsing
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def multi_host_url_schema(
max_length: int | None = None,
allowed_schemes: list[str] | None = None,
host_required: bool | None = None,
default_host: str | None = None,
default_port: int | None = None,
default_path: str | None = None,
preserve_empty_path: bool | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> MultiHostUrlSchema
Returns a schema that matches a URL value with possibly multiple hosts, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.multi_host_url_schema()
v = SchemaValidator(schema)
print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1'))
#> redis://localhost,0.0.0.0,127.0.0.1
MultiHostUrlSchema
The maximum length of the URL
The allowed URL schemes
Whether the URL must have a host
The default host to use if the URL does not have a host
The default port to use if the URL does not have a port
The default path to use if the URL does not have a path
Whether to preserve an empty path or convert it to ’/’, default False
Whether to use strict URL parsing
optional unique identifier of the schema, used to reference the schema in other places
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
def definitions_schema(
schema: CoreSchema,
definitions: list[CoreSchema],
) -> DefinitionsSchema
Build a schema that contains both an inner schema and a list of definitions which can be used within the inner schema.
from pydantic_core import SchemaValidator, core_schema
schema = core_schema.definitions_schema(
core_schema.list_schema(core_schema.definition_reference_schema('foobar')),
[core_schema.int_schema(ref='foobar')],
)
v = SchemaValidator(schema)
assert v.validate_python([1, 2, '3']) == [1, 2, 3]
DefinitionsSchema
The inner schema
definitions : list[CoreSchema]
List of definitions which can be referenced within inner schema
def definition_reference_schema(
schema_ref: str,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> DefinitionReferenceSchema
Returns a schema that points to a schema stored in “definitions”, this is useful for nested recursive models and also when you want to define validators separately from the main schema, e.g.:
from pydantic_core import SchemaValidator, core_schema
schema_definition = core_schema.definition_reference_schema('list-schema')
schema = core_schema.definitions_schema(
schema=schema_definition,
definitions=[
core_schema.list_schema(items_schema=schema_definition, ref='list-schema'),
],
)
v = SchemaValidator(schema)
assert v.validate_python([()]) == [[]]
DefinitionReferenceSchema
schema_ref : str
The schema ref to use for the definition reference schema
Any other information you want to include with the schema, not used by pydantic-core
serialization : SerSchema | None Default: None
Custom serialization schema
Values have the following meanings:
'always'means always use'unless-none'means use unless the value isNone'json'means use when serializing to JSON'json-unless-none'means use when serializing to JSON and the value is notNone
Default: Literal['always', 'unless-none', 'json', 'json-unless-none']