pydantic_core
SchemaValidator is the Python wrapper for pydantic-core’s Rust validation logic, internally it owns one
CombinedValidator which may in turn own more CombinedValidators which make up the full schema validator.
The title of the schema, as used in the heading of ValidationError.__str__().
Type: str
def validate_python(
input: Any,
strict: bool | None = None,
extra: ExtraBehavior | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None,
allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> Any
Validate a Python object against the schema and return the validated object.
Any — The validated object.
input : Any
The Python object to validate.
Whether to validate the object in strict mode.
If None, the value of CoreConfig.strict is used.
extra : ExtraBehavior | None Default: None
Whether to ignore, allow, or forbid extra data during model validation.
If None, the value of CoreConfig.extra_fields_behavior is used.
Whether to validate objects as inputs to models by extracting attributes.
If None, the value of CoreConfig.from_attributes is used.
The context to use for validation, this is passed to functional validators as
info.context.
An instance of a model set attributes on from validation, this is used when running
validation from the __init__ method of a model.
Whether to allow partial validation; if True errors in the last element of sequences
and mappings are ignored.
'trailing-strings' means any final unfinished JSON string is included in the result.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
ValidationError— If validation fails.Exception— Other error types maybe raised if internal errors occur.
def isinstance_python(
input: Any,
strict: bool | None = None,
extra: ExtraBehavior | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> bool
Similar to validate_python() but returns a boolean.
Arguments match validate_python(). This method will not raise ValidationErrors but will raise internal
errors.
bool — True if validation succeeds, False if validation fails.
def validate_json(
input: str | bytes | bytearray,
strict: bool | None = None,
extra: ExtraBehavior | None = None,
context: Any | None = None,
self_instance: Any | None = None,
allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> Any
Validate JSON data directly against the schema and return the validated Python object.
This method should be significantly faster than validate_python(json.loads(json_data)) as it avoids the
need to create intermediate Python objects
It also handles constructing the correct Python type even in strict mode, where
validate_python(json.loads(json_data)) would fail validation.
Any — The validated Python object.
The JSON data to validate.
Whether to validate the object in strict mode.
If None, the value of CoreConfig.strict is used.
extra : ExtraBehavior | None Default: None
Whether to ignore, allow, or forbid extra data during model validation.
If None, the value of CoreConfig.extra_fields_behavior is used.
The context to use for validation, this is passed to functional validators as
info.context.
An instance of a model set attributes on from validation.
Whether to allow partial validation; if True incomplete JSON will be parsed successfully
and errors in the last element of sequences and mappings are ignored.
'trailing-strings' means any final unfinished JSON string is included in the result.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
ValidationError— If validation fails or if the JSON data is invalid.Exception— Other error types maybe raised if internal errors occur.
def validate_strings(
input: _StringInput,
strict: bool | None = None,
extra: ExtraBehavior | None = None,
context: Any | None = None,
allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> Any
Validate a string against the schema and return the validated Python object.
This is similar to validate_json but applies to scenarios where the input will be a string but not
JSON data, e.g. URL fragments, query parameters, etc.
Any — The validated Python object.
The input as a string, or bytes/bytearray if strict=False.
Whether to validate the object in strict mode.
If None, the value of CoreConfig.strict is used.
extra : ExtraBehavior | None Default: None
Whether to ignore, allow, or forbid extra data during model validation.
If None, the value of CoreConfig.extra_fields_behavior is used.
The context to use for validation, this is passed to functional validators as
info.context.
Whether to allow partial validation; if True errors in the last element of sequences
and mappings are ignored.
'trailing-strings' means any final unfinished JSON string is included in the result.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
ValidationError— If validation fails or if the JSON data is invalid.Exception— Other error types maybe raised if internal errors occur.
def validate_assignment(
obj: Any,
field_name: str,
field_value: Any,
strict: bool | None = None,
extra: ExtraBehavior | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]
Validate an assignment to a field on a model.
dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]] — Either the model dict or a tuple of (model_data, model_extra, fields_set)
obj : Any
The model instance being assigned to.
field_name : str
The name of the field to validate assignment for.
field_value : Any
The value to assign to the field.
Whether to validate the object in strict mode.
If None, the value of CoreConfig.strict is used.
extra : ExtraBehavior | None Default: None
Whether to ignore, allow, or forbid extra data during model validation.
If None, the value of CoreConfig.extra_fields_behavior is used.
Whether to validate objects as inputs to models by extracting attributes.
If None, the value of CoreConfig.from_attributes is used.
The context to use for validation, this is passed to functional validators as
info.context.
Whether to use the field’s alias when validating against the provided input data.
Whether to use the field’s name when validating against the provided input data.
ValidationError— If validation fails.Exception— Other error types maybe raised if internal errors occur.
def get_default_value(strict: bool | None = None, context: Any = None) -> Some | None
Get the default value for the schema, including running default value validation.
Some | None — None if the schema has no default value, otherwise a Some containing the default.
Whether to validate the default value in strict mode.
If None, the value of CoreConfig.strict is used.
context : Any Default: None
The context to use for validation, this is passed to functional validators as
info.context.
ValidationError— If validation fails.Exception— Other error types maybe raised if internal errors occur.
SchemaSerializer is the Python wrapper for pydantic-core’s Rust serialization logic, internally it owns one
CombinedSerializer which may in turn own more CombinedSerializers which make up the full schema serializer.
def to_python(
value: Any,
mode: str | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None,
) -> Any
Serialize/marshal a Python object to a Python object including transforming and filtering data.
Any — The serialized Python object.
value : Any
The Python object to serialize.
The serialization mode to use, either 'python' or 'json', defaults to 'python'. In JSON mode,
all values are converted to JSON compatible types, e.g. None, int, float, str, list, dict.
include : _IncEx | None Default: None
A set of fields to include, if None all fields are included.
exclude : _IncEx | None Default: None
A set of fields to exclude, if None no fields are excluded.
Whether to use the alias names of fields.
exclude_unset : bool Default: False
Whether to exclude fields that are not set,
e.g. are not included in __pydantic_fields_set__.
exclude_defaults : bool Default: False
Whether to exclude fields that are equal to their default value.
exclude_none : bool Default: False
Whether to exclude fields that have a value of None.
exclude_computed_fields : bool Default: False
Whether to exclude computed fields.
round_trip : bool Default: False
Whether to enable serialization and validation round-trip support.
How to handle invalid fields. False/“none” ignores them, True/“warn” logs errors,
“error” raises a PydanticSerializationError.
A function to call when an unknown value is encountered,
if None a PydanticSerializationError error is raised.
serialize_as_any : bool Default: False
Whether to serialize fields with duck-typing serialization behavior.
The context to use for serialization, this is passed to functional serializers as
info.context.
PydanticSerializationError— If serialization fails and nofallbackfunction is provided.
def to_json(
value: Any,
indent: int | None = None,
ensure_ascii: bool = False,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None,
) -> bytes
Serialize a Python object to JSON including transforming and filtering data.
bytes — JSON bytes.
value : Any
The Python object to serialize.
If None, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
ensure_ascii : bool Default: False
If True, the output is guaranteed to have all incoming non-ASCII characters escaped.
If False (the default), these characters will be output as-is.
include : _IncEx | None Default: None
A set of fields to include, if None all fields are included.
exclude : _IncEx | None Default: None
A set of fields to exclude, if None no fields are excluded.
Whether to use the alias names of fields.
exclude_unset : bool Default: False
Whether to exclude fields that are not set,
e.g. are not included in __pydantic_fields_set__.
exclude_defaults : bool Default: False
Whether to exclude fields that are equal to their default value.
exclude_none : bool Default: False
Whether to exclude fields that have a value of None.
exclude_computed_fields : bool Default: False
Whether to exclude computed fields.
round_trip : bool Default: False
Whether to enable serialization and validation round-trip support.
How to handle invalid fields. False/“none” ignores them, True/“warn” logs errors,
“error” raises a PydanticSerializationError.
A function to call when an unknown value is encountered,
if None a PydanticSerializationError error is raised.
serialize_as_any : bool Default: False
Whether to serialize fields with duck-typing serialization behavior.
The context to use for serialization, this is passed to functional serializers as
info.context.
PydanticSerializationError— If serialization fails and nofallbackfunction is provided.
Bases: ValueError
ValidationError is the exception raised by pydantic-core when validation fails, it contains a list of errors
which detail why validation failed.
The title of the error, as used in the heading of str(validation_error).
Type: str
@classmethod
def from_exception_data(
cls,
title: str,
line_errors: list[InitErrorDetails],
input_type: Literal['python', 'json'] = 'python',
hide_input: bool = False,
) -> Self
Python constructor for a Validation Error.
title : str
The title of the error, as used in the heading of str(validation_error)
line_errors : list[InitErrorDetails]
A list of InitErrorDetails which contain information
about errors that occurred during validation.
input_type : Literal[‘python’, ‘json’] Default: 'python'
Whether the error is for a Python object or JSON.
hide_input : bool Default: False
Whether to hide the input value in the error message.
def error_count() -> int
int — The number of errors in the validation error.
def errors(
include_url: bool = True,
include_context: bool = True,
include_input: bool = True,
) -> list[ErrorDetails]
Details about each error in the validation error.
list[ErrorDetails] — A list of ErrorDetails for each error in the validation error.
include_url : bool Default: True
Whether to include a URL to documentation on the error each error.
include_context : bool Default: True
Whether to include the context of each error.
include_input : bool Default: True
Whether to include the input value of each error.
def json(
indent: int | None = None,
include_url: bool = True,
include_context: bool = True,
include_input: bool = True,
) -> str
Same as errors() but returns a JSON string.
str — a JSON string.
The number of spaces to indent the JSON by, or None for no indentation - compact JSON.
include_url : bool Default: True
Whether to include a URL to documentation on the error each error.
include_context : bool Default: True
Whether to include the context of each error.
include_input : bool Default: True
Whether to include the input value of each error.
Bases: _TypedDict
The type of error that occurred, this is an identifier designed for programmatic use that will change rarely or never.
type is unique for each error message, and can hence be used as an identifier to build custom error messages.
Type: str
Tuple of strings and ints identifying where in the schema the error occurred.
A human readable error message.
Type: str
The input data at this loc that caused the error.
Type: _Any
Values which are required to render the error message, and could hence be useful in rendering custom error messages. Also useful for passing custom error data forward.
Type: _NotRequired[dict[str, _Any]]
The documentation URL giving information about the error. No URL is available if
a PydanticCustomError is used.
Type: _NotRequired[str]
Bases: _TypedDict
The type of error that occurred, this should be a “slug” identifier that changes rarely or never.
Type: str | PydanticCustomError
Tuple of strings and ints identifying where in the schema the error occurred.
Type: _NotRequired[tuple[int | str, …]]
The input data at this loc that caused the error.
Type: _Any
Values which are required to render the error message, and could hence be useful in rendering custom error messages. Also useful for passing custom error data forward.
Type: _NotRequired[dict[str, _Any]]
Bases: Exception
Information about errors that occur while building a SchemaValidator
or SchemaSerializer.
def error_count() -> int
int — The number of errors in the schema.
def errors() -> list[ErrorDetails]
list[ErrorDetails] — A list of ErrorDetails for each error in the schema.
Bases: ValueError
A custom exception providing flexible error handling for Pydantic validators.
You can raise this error in custom validators when you’d like flexibility in regards to the error type, message, and context.
error_type : LiteralString
The error type.
message_template : LiteralString
The message template.
The data to inject into the message template.
Values which are required to render the error message, and could hence be useful in passing error data forward.
The error type associated with the error. For consistency with Pydantic, this is typically a snake_case string.
Type: str
The message template associated with the error. This is a string that can be formatted with context variables in \{curly_braces\}.
Type: str
def message() -> str
The formatted message associated with the error. This presents as the message template with context variables appropriately injected.
Bases: ValueError
A helper class for raising exceptions that mimic Pydantic’s built-in exceptions, with more flexibility in regards to context.
Unlike PydanticCustomError, the error_type argument must be a known ErrorType.
The error type.
The data to inject into the message template.
Values which are required to render the error message, and could hence be useful in passing error data forward.
The type of the error.
Type: ErrorType
The message template associated with the provided error type. This is a string that can be formatted with context variables in \{curly_braces\}.
Type: str
def message() -> str
The formatted message associated with the error. This presents as the message template with context variables appropriately injected.
Bases: Exception
An exception to signal that a field should be omitted from a generated result.
This could span from omitting a field from a JSON Schema to omitting a field from a serialized result. Upcoming: more robust support for using PydanticOmit in custom serializers is still in development. Right now, this is primarily used in the JSON Schema generation process.
For a more in depth example / explanation, see the customizing JSON schema docs.
Bases: Exception
An exception to signal that standard validation either failed or should be skipped, and the default value should be used instead.
This warning can be raised in custom valiation functions to redirect the flow of validation.
For an additional example, see the validating partial json data section of the Pydantic documentation.
Bases: ValueError
An error raised when an issue occurs during serialization.
In custom serializers, this error can be used to indicate that serialization has failed.
message : str
The message associated with the error.
Bases: ValueError
An error raised when an unexpected value is encountered during serialization.
This error is often caught and coerced into a warning, as pydantic-core generally makes a best attempt
at serializing values, in contrast with validation where errors are eagerly raised.
This is often used internally in pydantic-core when unexpected types are encountered during serialization,
but it can also be used by users in custom serializers, as seen above.
message : str
The message associated with the unexpected value.
Bases: SupportsAllComparisons
A URL type, internal logic uses the url rust crate originally developed by Mozilla.
Bases: SupportsAllComparisons
A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. https://foo.com,bar.com/path.
Internal URL logic uses the url rust crate originally developed by Mozilla.
Bases: _TypedDict
A host part of a multi-host URL.
The username part of this host, or None.
The password part of this host, or None.
The host part of this host, or None.
The port part of this host, or None.
A construct used to store arguments and keyword arguments for a function call.
This data structure is generally used to store information for core schemas associated with functions (like in an arguments schema). This data structure is also currently used for some validation against dataclasses.
The arguments (inherently ordered) for a function call.
The keyword arguments for a function call.
Bases: Generic[_T]
Similar to Rust’s Option::Some type, this
identifies a value as being present, and provides a way to access it.
Generally used in a union with None to different between “some value which could be None” and no value.
Returns the value wrapped by Some.
Type: _T
Bases: tzinfo
An pydantic-core implementation of the abstract datetime.tzinfo class.
def tzname(dt: datetime.datetime | None) -> str | None
Return the time zone name corresponding to the datetime object dt, as a string.
For more info, see tzinfo.tzname.
def utcoffset(dt: datetime.datetime | None) -> datetime.timedelta | None
Return offset of local time from UTC, as a timedelta object that is positive east of UTC. If local time is west of UTC, this should be negative.
More info can be found at tzinfo.utcoffset.
def dst(dt: datetime.datetime | None) -> datetime.timedelta | None
Return the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn’t known.
More info can be found attzinfo.dst.
def fromutc(dt: datetime.datetime) -> datetime.datetime
Adjust the date and time data associated datetime object dt, returning an equivalent datetime in self’s local time.
More info can be found at tzinfo.fromutc.
Bases: _TypedDict
Gives information about errors.
The type of error that occurred, this should be a “slug” identifier that changes rarely or never.
Type: ErrorType
String template to render a human readable error message from using context, when the input is Python.
Type: str
Example of a human readable error message, when the input is Python.
Type: str
String template to render a human readable error message from using context, when the input is JSON data.
Type: _NotRequired[str]
Example of a human readable error message, when the input is JSON data.
Type: _NotRequired[str]
Example of context values.
def to_json(
value: Any,
indent: int | None = None,
ensure_ascii: bool = False,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None,
) -> bytes
Serialize a Python object to JSON including transforming and filtering data.
This is effectively a standalone version of SchemaSerializer.to_json.
bytes — JSON bytes.
value : Any
The Python object to serialize.
If None, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
ensure_ascii : bool Default: False
If True, the output is guaranteed to have all incoming non-ASCII characters escaped.
If False (the default), these characters will be output as-is.
include : _IncEx | None Default: None
A set of fields to include, if None all fields are included.
exclude : _IncEx | None Default: None
A set of fields to exclude, if None no fields are excluded.
by_alias : bool Default: True
Whether to use the alias names of fields.
exclude_none : bool Default: False
Whether to exclude fields that have a value of None.
round_trip : bool Default: False
Whether to enable serialization and validation round-trip support.
timedelta_mode : Literal[‘iso8601’, ‘float’] Default: 'iso8601'
How to serialize timedelta objects, either 'iso8601' or 'float'.
temporal_mode : Literal[‘iso8601’, ‘seconds’, ‘milliseconds’] Default: 'iso8601'
How to serialize datetime-like objects (datetime, date, time), either 'iso8601', 'seconds', or 'milliseconds'.
iso8601 returns an ISO 8601 string; seconds returns the Unix timestamp in seconds as a float; milliseconds returns the Unix timestamp in milliseconds as a float.
bytes_mode : Literal[‘utf8’, ‘base64’, ‘hex’] Default: 'utf8'
How to serialize bytes objects, either 'utf8', 'base64', or 'hex'.
inf_nan_mode : Literal[‘null’, ‘constants’, ‘strings’] Default: 'constants'
How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.
serialize_unknown : bool Default: False
Attempt to serialize unknown types, str(value) will be used, if that fails
"<Unserializable \{value_type\} object>" will be used.
A function to call when an unknown value is encountered,
if None a PydanticSerializationError error is raised.
serialize_as_any : bool Default: False
Whether to serialize fields with duck-typing serialization behavior.
The context to use for serialization, this is passed to functional serializers as
info.context.
PydanticSerializationError— If serialization fails and nofallbackfunction is provided.
def from_json(
data: str | bytes | bytearray,
allow_inf_nan: bool = True,
cache_strings: bool | Literal['all', 'keys', 'none'] = True,
allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
) -> Any
Deserialize JSON data to a Python object.
This is effectively a faster version of json.loads(), with some extra functionality.
Any — The deserialized Python object.
The JSON data to deserialize.
allow_inf_nan : bool Default: True
Whether to allow Infinity, -Infinity and NaN values as json.loads() does by default.
Whether to cache strings to avoid constructing new Python objects,
this should have a significant impact on performance while increasing memory usage slightly,
all/True means cache all strings, keys means cache only dict keys, none/False means no caching.
Whether to allow partial deserialization, if True JSON data is returned if the end of the
input is reached before the full object is deserialized, e.g. ["aa", "bb", "c would return ['aa', 'bb'].
'trailing-strings' means any final unfinished JSON string is included in the result.
ValueError— If deserialization fails.
def to_jsonable_python(
value: Any,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None,
) -> Any
Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data.
This is effectively a standalone version of
SchemaSerializer.to_python(mode='json').
Any — The serialized Python object.
value : Any
The Python object to serialize.
include : _IncEx | None Default: None
A set of fields to include, if None all fields are included.
exclude : _IncEx | None Default: None
A set of fields to exclude, if None no fields are excluded.
by_alias : bool Default: True
Whether to use the alias names of fields.
exclude_none : bool Default: False
Whether to exclude fields that have a value of None.
round_trip : bool Default: False
Whether to enable serialization and validation round-trip support.
timedelta_mode : Literal[‘iso8601’, ‘float’] Default: 'iso8601'
How to serialize timedelta objects, either 'iso8601' or 'float'.
temporal_mode : Literal[‘iso8601’, ‘seconds’, ‘milliseconds’] Default: 'iso8601'
How to serialize datetime-like objects (datetime, date, time), either 'iso8601', 'seconds', or 'milliseconds'.
iso8601 returns an ISO 8601 string; seconds returns the Unix timestamp in seconds as a float; milliseconds returns the Unix timestamp in milliseconds as a float.
bytes_mode : Literal[‘utf8’, ‘base64’, ‘hex’] Default: 'utf8'
How to serialize bytes objects, either 'utf8', 'base64', or 'hex'.
inf_nan_mode : Literal[‘null’, ‘constants’, ‘strings’] Default: 'constants'
How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.
serialize_unknown : bool Default: False
Attempt to serialize unknown types, str(value) will be used, if that fails
"<Unserializable \{value_type\} object>" will be used.
A function to call when an unknown value is encountered,
if None a PydanticSerializationError error is raised.
serialize_as_any : bool Default: False
Whether to serialize fields with duck-typing serialization behavior.
The context to use for serialization, this is passed to functional serializers as
info.context.
PydanticSerializationError— If serialization fails and nofallbackfunction is provided.
Type: str