pydantic_core
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.
Type: tuple[Any, …]
The keyword arguments for a function call.
Type: dict[str, Any] | None
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: 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.
The error type.
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.
Type: dict[str, Any] | None
The message template associated with the error. This is a string that can be formatted with context variables in \{curly_braces\}.
Type: str
The error type associated with the error. For consistency with Pydantic, this is typically a snake_case string.
Type: str
def message() -> str
The formatted message associated with the error. This presents as the message template with context variables appropriately injected.
str
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.
Type: dict[str, Any] | None
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
The type of the error.
Type: ErrorType
def message() -> str
The formatted message associated with the error. This presents as the message template with context variables appropriately injected.
str
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: ValueError
An error raised when an issue occurs during serialization.
In custom serializers, this error can be used to indicate that serialization has failed.
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.
The message associated with the unexpected value.
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.
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_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.
The Python object to serialize.
If None, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
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.
A set of fields to include, if None all fields are included.
A set of fields to exclude, if None no fields are excluded.
Whether to use the alias names of fields.
Whether to exclude fields that are not set,
e.g. are not included in __pydantic_fields_set__.
Whether to exclude fields that are equal to their default value.
Whether to exclude fields that have a value of None.
Whether to exclude computed fields.
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.
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_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.
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.
A set of fields to include, if None all fields are included.
A set of fields to exclude, if None no fields are excluded.
Whether to use the alias names of fields.
Whether to exclude fields that are not set,
e.g. are not included in __pydantic_fields_set__.
Whether to exclude fields that are equal to their default value.
Whether to exclude fields that have a value of None.
Whether to exclude computed fields.
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.
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.
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 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.
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.
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_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)
The model instance being assigned to.
The name of the field to validate assignment for.
The value to assign to the field.
Whether to validate the object in strict mode.
If None, the value of CoreConfig.strict is used.
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 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.
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_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.
The Python object to validate.
Whether to validate the object in strict mode.
If None, the value of CoreConfig.strict is used.
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 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.
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.
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: SupportsAllComparisons
A URL type, internal logic uses the url rust crate originally developed by Mozilla.
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
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.
Whether to include a URL to documentation on the error each error.
Whether to include the context of each error.
Whether to include the input value of each error.
@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.
Self
The title of the error, as used in the heading of str(validation_error)
A list of InitErrorDetails which contain information
about errors that occurred during validation.
Whether the error is for a Python object or JSON.
Whether to hide the input value in the error message.
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.
Whether to include a URL to documentation on the error each error.
Whether to include the context of each error.
Whether to include the input value of each error.
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.
The Python object to serialize.
If None, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
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.
A set of fields to include, if None all fields are included.
A set of fields to exclude, if None no fields are excluded.
Whether to use the alias names of fields.
Whether to exclude fields that have a value of None.
Whether to enable serialization and validation round-trip support.
How to serialize timedelta objects, either 'iso8601' or 'float'.
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.
How to serialize bytes objects, either 'utf8', 'base64', or 'hex'.
How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.
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.
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_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.
The Python object to serialize.
A set of fields to include, if None all fields are included.
A set of fields to exclude, if None no fields are excluded.
Whether to use the alias names of fields.
Whether to exclude fields that have a value of None.
Whether to enable serialization and validation round-trip support.
How to serialize timedelta objects, either 'iso8601' or 'float'.
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.
How to serialize bytes objects, either 'utf8', 'base64', or 'hex'.
How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.
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.
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.