Skip to content

pydantic_core

__version__ module-attribute

__version__: str

SchemaValidator

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.

title property

title: str

The title of the schema, as used in the heading of ValidationError.__str__().

validate_python

validate_python(
    input: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    self_instance: Any | None = None
) -> Any

Validate a Python object against the schema and return the validated object.

Parameters:

Name Type Description Default
input Any

The Python object to validate.

required
strict bool | None

Whether to validate the object in strict mode. If None, the value of CoreConfig.strict is used.

None
from_attributes bool | None

Whether to validate objects as inputs to models by extracting attributes. If None, the value of CoreConfig.from_attributes is used.

None
context Any | None

The context to use for validation, this is passed to functional validators as info.context.

None
self_instance Any | None

An instance of a model set attributes on from validation, this is used when running validation from the __init__ method of a model.

None

Raises:

Type Description
ValidationError

If validation fails.

Exception

Other error types maybe raised if internal errors occur.

Returns:

Type Description
Any

The validated object.

isinstance_python

isinstance_python(
    input: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    self_instance: Any | 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.

Returns:

Type Description
bool

True if validation succeeds, False if validation fails.

validate_json

validate_json(
    input: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: Any | None = None,
    self_instance: Any | 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.

Parameters:

Name Type Description Default
input str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to validate the object in strict mode. If None, the value of CoreConfig.strict is used.

None
context Any | None

The context to use for validation, this is passed to functional validators as info.context.

None
self_instance Any | None

An instance of a model set attributes on from validation.

None

Raises:

Type Description
ValidationError

If validation fails or if the JSON data is invalid.

Exception

Other error types maybe raised if internal errors occur.

Returns:

Type Description
Any

The validated Python object.

validate_strings

validate_strings(
    input: _StringInput,
    *,
    strict: bool | None = None,
    context: Any | 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.

Parameters:

Name Type Description Default
input _StringInput

The input as a string, or bytes/bytearray if strict=False.

required
strict bool | None

Whether to validate the object in strict mode. If None, the value of CoreConfig.strict is used.

None
context Any | None

The context to use for validation, this is passed to functional validators as info.context.

None

Raises:

Type Description
ValidationError

If validation fails or if the JSON data is invalid.

Exception

Other error types maybe raised if internal errors occur.

Returns:

Type Description
Any

The validated Python object.

validate_assignment

validate_assignment(
    obj: Any,
    field_name: str,
    field_value: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None
) -> (
    dict[str, Any]
    | tuple[dict[str, Any], dict[str, Any] | None, set[str]]
)

Validate an assignment to a field on a model.

Parameters:

Name Type Description Default
obj Any

The model instance being assigned to.

required
field_name str

The name of the field to validate assignment for.

required
field_value Any

The value to assign to the field.

required
strict bool | None

Whether to validate the object in strict mode. If None, the value of CoreConfig.strict is used.

None
from_attributes bool | None

Whether to validate objects as inputs to models by extracting attributes. If None, the value of CoreConfig.from_attributes is used.

None
context Any | None

The context to use for validation, this is passed to functional validators as info.context.

None

Raises:

Type Description
ValidationError

If validation fails.

Exception

Other error types maybe raised if internal errors occur.

Returns:

Type Description
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)

get_default_value

get_default_value(
    *, strict: bool | None = None, context: Any = None
) -> Some | None

Get the default value for the schema, including running default value validation.

Parameters:

Name Type Description Default
strict bool | None

Whether to validate the default value in strict mode. If None, the value of CoreConfig.strict is used.

None
context Any

The context to use for validation, this is passed to functional validators as info.context.

None

Raises:

Type Description
ValidationError

If validation fails.

Exception

Other error types maybe raised if internal errors occur.

Returns:

Type Description
Some | None

None if the schema has no default value, otherwise a Some containing the default.

SchemaSerializer

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.

to_python

to_python(
    value: Any,
    *,
    mode: str | None = None,
    include: _IncEx = None,
    exclude: _IncEx = None,
    by_alias: bool = True,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: 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.

Parameters:

Name Type Description Default
value Any

The Python object to serialize.

required
mode str | None

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.

None
include _IncEx

A set of fields to include, if None all fields are included.

None
exclude _IncEx

A set of fields to exclude, if None no fields are excluded.

None
by_alias bool

Whether to use the alias names of fields.

True
exclude_unset bool

Whether to exclude fields that are not set, e.g. are not included in __pydantic_fields_set__.

False
exclude_defaults bool

Whether to exclude fields that are equal to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

Whether to enable serialization and validation round-trip support.

False
warnings bool | Literal['none', 'warn', 'error']

How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors, "error" raises a PydanticSerializationError.

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered, if None a PydanticSerializationError error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False
context Any | None

The context to use for serialization, this is passed to functional serializers as info.context.

None

Raises:

Type Description
PydanticSerializationError

If serialization fails and no fallback function is provided.

Returns:

Type Description
Any

The serialized Python object.

to_json

to_json(
    value: Any,
    *,
    indent: int | None = None,
    include: _IncEx = None,
    exclude: _IncEx = None,
    by_alias: bool = True,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: 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.

Parameters:

Name Type Description Default
value Any

The Python object to serialize.

required
indent int | None

If None, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.

None
include _IncEx

A set of fields to include, if None all fields are included.

None
exclude _IncEx

A set of fields to exclude, if None no fields are excluded.

None
by_alias bool

Whether to use the alias names of fields.

True
exclude_unset bool

Whether to exclude fields that are not set, e.g. are not included in __pydantic_fields_set__.

False
exclude_defaults bool

Whether to exclude fields that are equal to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

Whether to enable serialization and validation round-trip support.

False
warnings bool | Literal['none', 'warn', 'error']

How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors, "error" raises a PydanticSerializationError.

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered, if None a PydanticSerializationError error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False
context Any | None

The context to use for serialization, this is passed to functional serializers as info.context.

None

Raises:

Type Description
PydanticSerializationError

If serialization fails and no fallback function is provided.

Returns:

Type Description
bytes

JSON bytes.

ValidationError

Bases: ValueError

ValidationError is the exception raised by pydantic-core when validation fails, it contains a list of errors which detail why validation failed.

title property

title: str

The title of the error, as used in the heading of str(validation_error).

from_exception_data staticmethod

from_exception_data(
    title: str,
    line_errors: list[InitErrorDetails],
    input_type: Literal["python", "json"] = "python",
    hide_input: bool = False,
) -> ValidationError

Python constructor for a Validation Error.

The API for constructing validation errors will probably change in the future, hence the static method rather than __init__.

Parameters:

Name Type Description Default
title str

The title of the error, as used in the heading of str(validation_error)

required
line_errors list[InitErrorDetails]

A list of InitErrorDetails which contain information about errors that occurred during validation.

required
input_type Literal['python', 'json']

Whether the error is for a Python object or JSON.

'python'
hide_input bool

Whether to hide the input value in the error message.

False

error_count

error_count() -> int

Returns:

Type Description
int

The number of errors in the validation error.

errors

errors(
    *,
    include_url: bool = True,
    include_context: bool = True,
    include_input: bool = True
) -> list[ErrorDetails]

Details about each error in the validation error.

Parameters:

Name Type Description Default
include_url bool

Whether to include a URL to documentation on the error each error.

True
include_context bool

Whether to include the context of each error.

True
include_input bool

Whether to include the input value of each error.

True

Returns:

Type Description
list[ErrorDetails]

A list of ErrorDetails for each error in the validation error.

json

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.

Parameters:

Name Type Description Default
indent int | None

The number of spaces to indent the JSON by, or None for no indentation - compact JSON.

None
include_url bool

Whether to include a URL to documentation on the error each error.

True
include_context bool

Whether to include the context of each error.

True
include_input bool

Whether to include the input value of each error.

True

Returns:

Type Description
str

a JSON string.

ErrorDetails

Bases: TypedDict

type instance-attribute

type: str

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.

loc instance-attribute

loc: tuple[int | str, ...]

Tuple of strings and ints identifying where in the schema the error occurred.

msg instance-attribute

msg: str

A human readable error message.

input instance-attribute

input: Any

The input data at this loc that caused the error.

ctx instance-attribute

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.

InitErrorDetails

Bases: TypedDict

type instance-attribute

The type of error that occurred, this should a "slug" identifier that changes rarely or never.

loc instance-attribute

loc: NotRequired[tuple[int | str, ...]]

Tuple of strings and ints identifying where in the schema the error occurred.

input instance-attribute

input: Any

The input data at this loc that caused the error.

ctx instance-attribute

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.

SchemaError

Bases: Exception

Information about errors that occur while building a SchemaValidator or SchemaSerializer.

error_count

error_count() -> int

Returns:

Type Description
int

The number of errors in the schema.

errors

errors() -> list[ErrorDetails]

Returns:

Type Description
list[ErrorDetails]

A list of ErrorDetails for each error in the schema.

PydanticCustomError

Bases: ValueError

PydanticKnownError

Bases: ValueError

PydanticOmit

Bases: Exception

PydanticSerializationError

Bases: ValueError

PydanticSerializationUnexpectedValue

Bases: ValueError

Url

Bases: SupportsAllComparisons

A URL type, internal logic uses the url rust crate originally developed by Mozilla.

scheme property

scheme: str

The scheme part of the URL.

e.g. https in https://user:pass@host:port/path?query#fragment

username property

username: str | None

The username part of the URL, or None.

e.g. user in https://user:pass@host:port/path?query#fragment

password property

password: str | None

The password part of the URL, or None.

e.g. pass in https://user:pass@host:port/path?query#fragment

host property

host: str | None

The host part of the URL, or None.

If the URL must be punycode encoded, this is the encoded host, e.g if the input URL is https://£££.com, host will be xn--9aaa.com

port property

port: int | None

The port part of the URL, or None.

e.g. port in https://user:pass@host:port/path?query#fragment

path property

path: str | None

The path part of the URL, or None.

e.g. /path in https://user:pass@host:port/path?query#fragment

query property

query: str | None

The query part of the URL, or None.

e.g. query in https://user:pass@host:port/path?query#fragment

fragment property

fragment: str | None

The fragment part of the URL, or None.

e.g. fragment in https://user:pass@host:port/path?query#fragment

unicode_host

unicode_host() -> str | None

The host part of the URL as a unicode string, or None.

e.g. host in https://user:pass@host:port/path?query#fragment

If the URL must be punycode encoded, this is the decoded host, e.g if the input URL is https://£££.com, unicode_host() will be £££.com

query_params

query_params() -> list[tuple[str, str]]

The query part of the URL as a list of key-value pairs.

e.g. [('foo', 'bar')] in https://user:pass@host:port/path?foo=bar#fragment

unicode_string

unicode_string() -> str

The URL as a unicode string, unlike __str__() this will not punycode encode the host.

If the URL must be punycode encoded, this is the decoded string, e.g if the input URL is https://£££.com, unicode_string() will be https://£££.com

build classmethod

build(
    *,
    scheme: str,
    username: str | None = None,
    password: str | None = None,
    host: str,
    port: int | None = None,
    path: str | None = None,
    query: str | None = None,
    fragment: str | None = None
) -> Self

Build a new Url instance from its component parts.

Parameters:

Name Type Description Default
scheme str

The scheme part of the URL.

required
username str | None

The username part of the URL, or omit for no username.

None
password str | None

The password part of the URL, or omit for no password.

None
host str

The host part of the URL.

required
port int | None

The port part of the URL, or omit for no port.

None
path str | None

The path part of the URL, or omit for no path.

None
query str | None

The query part of the URL, or omit for no query.

None
fragment str | None

The fragment part of the URL, or omit for no fragment.

None

Returns:

Type Description
Self

An instance of URL

MultiHostUrl

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.

scheme property

scheme: str

The scheme part of the URL.

e.g. https in https://foo.com,bar.com/path?query#fragment

path property

path: str | None

The path part of the URL, or None.

e.g. /path in https://foo.com,bar.com/path?query#fragment

query property

query: str | None

The query part of the URL, or None.

e.g. query in https://foo.com,bar.com/path?query#fragment

fragment property

fragment: str | None

The fragment part of the URL, or None.

e.g. fragment in https://foo.com,bar.com/path?query#fragment

query_params

query_params() -> list[tuple[str, str]]

The query part of the URL as a list of key-value pairs.

e.g. [('foo', 'bar')] in https://foo.com,bar.com/path?query#fragment

hosts

hosts() -> list[MultiHostHost]

The hosts of the MultiHostUrl as MultiHostHost typed dicts.

from pydantic_core import MultiHostUrl

mhu = MultiHostUrl('https://foo.com:123,foo:[email protected]/path')
print(mhu.hosts())
"""
[
    {'username': None, 'password': None, 'host': 'foo.com', 'port': 123},
    {'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443}
]
Returns: A list of dicts, each representing a host.

unicode_string

unicode_string() -> str

The URL as a unicode string, unlike __str__() this will not punycode encode the hosts.

build classmethod

build(
    *,
    scheme: str,
    hosts: list[MultiHostHost] | None = None,
    username: str | None = None,
    password: str | None = None,
    host: str | None = None,
    port: int | None = None,
    path: str | None = None,
    query: str | None = None,
    fragment: str | None = None
) -> Self

Build a new MultiHostUrl instance from its component parts.

This method takes either hosts - a list of MultiHostHost typed dicts, or the individual components username, password, host and port.

Parameters:

Name Type Description Default
scheme str

The scheme part of the URL.

required
hosts list[MultiHostHost] | None

Multiple hosts to build the URL from.

None
username str | None

The username part of the URL.

None
password str | None

The password part of the URL.

None
host str | None

The host part of the URL.

None
port int | None

The port part of the URL.

None
path str | None

The path part of the URL.

None
query str | None

The query part of the URL, or omit for no query.

None
fragment str | None

The fragment part of the URL, or omit for no fragment.

None

Returns:

Type Description
Self

An instance of MultiHostUrl

MultiHostHost

Bases: TypedDict

A host part of a multi-host URL.

username instance-attribute

username: str | None

The username part of this host, or None.

password instance-attribute

password: str | None

The password part of this host, or None.

host instance-attribute

host: str | None

The host part of this host, or None.

port instance-attribute

port: int | None

The port part of this host, or None.

ArgsKwargs

Some

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.

value property

value: _T

Returns the value wrapped by Some.

TzInfo

Bases: tzinfo

ErrorTypeInfo

Bases: TypedDict

Gives information about errors.

type instance-attribute

type: ErrorType

The type of error that occurred, this should a "slug" identifier that changes rarely or never.

message_template_python instance-attribute

message_template_python: str

String template to render a human readable error message from using context, when the input is Python.

example_message_python instance-attribute

example_message_python: str

Example of a human readable error message, when the input is Python.

message_template_json instance-attribute

message_template_json: NotRequired[str]

String template to render a human readable error message from using context, when the input is JSON data.

example_message_json instance-attribute

example_message_json: NotRequired[str]

Example of a human readable error message, when the input is JSON data.

example_context instance-attribute

example_context: dict[str, Any] | None

Example of context values.

to_json

to_json(
    value: Any,
    *,
    indent: int | None = None,
    include: _IncEx = None,
    exclude: _IncEx = None,
    by_alias: bool = True,
    exclude_none: bool = False,
    round_trip: bool = False,
    timedelta_mode: Literal["iso8601", "float"] = "iso8601",
    bytes_mode: Literal["utf8", "base64"] = "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.

Parameters:

Name Type Description Default
value Any

The Python object to serialize.

required
indent int | None

If None, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.

None
include _IncEx

A set of fields to include, if None all fields are included.

None
exclude _IncEx

A set of fields to exclude, if None no fields are excluded.

None
by_alias bool

Whether to use the alias names of fields.

True
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

Whether to enable serialization and validation round-trip support.

False
timedelta_mode Literal['iso8601', 'float']

How to serialize timedelta objects, either 'iso8601' or 'float'.

'iso8601'
bytes_mode Literal['utf8', 'base64']

How to serialize bytes objects, either 'utf8' or 'base64'.

'utf8'
inf_nan_mode Literal['null', 'constants', 'strings']

How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.

'constants'
serialize_unknown bool

Attempt to serialize unknown types, str(value) will be used, if that fails "<Unserializable {value_type} object>" will be used.

False
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered, if None a PydanticSerializationError error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False
context Any | None

The context to use for serialization, this is passed to functional serializers as info.context.

None

Raises:

Type Description
PydanticSerializationError

If serialization fails and no fallback function is provided.

Returns:

Type Description
bytes

JSON bytes.

from_json

from_json(
    data: str | bytes | bytearray,
    *,
    allow_inf_nan: bool = True,
    cache_strings: (
        bool | Literal["all", "keys", "none"]
    ) = True,
    allow_partial: bool = False
) -> Any

Deserialize JSON data to a Python object.

This is effectively a faster version of json.loads(), with some extra functionality.

Parameters:

Name Type Description Default
data str | bytes | bytearray

The JSON data to deserialize.

required
allow_inf_nan bool

Whether to allow Infinity, -Infinity and NaN values as json.loads() does by default.

True
cache_strings bool | Literal['all', 'keys', 'none']

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.

True
allow_partial bool

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'].

False

Raises:

Type Description
ValueError

If deserialization fails.

Returns:

Type Description
Any

The deserialized Python object.

to_jsonable_python

to_jsonable_python(
    value: Any,
    *,
    include: _IncEx = None,
    exclude: _IncEx = None,
    by_alias: bool = True,
    exclude_none: bool = False,
    round_trip: bool = False,
    timedelta_mode: Literal["iso8601", "float"] = "iso8601",
    bytes_mode: Literal["utf8", "base64"] = "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').

Parameters:

Name Type Description Default
value Any

The Python object to serialize.

required
include _IncEx

A set of fields to include, if None all fields are included.

None
exclude _IncEx

A set of fields to exclude, if None no fields are excluded.

None
by_alias bool

Whether to use the alias names of fields.

True
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

Whether to enable serialization and validation round-trip support.

False
timedelta_mode Literal['iso8601', 'float']

How to serialize timedelta objects, either 'iso8601' or 'float'.

'iso8601'
bytes_mode Literal['utf8', 'base64']

How to serialize bytes objects, either 'utf8' or 'base64'.

'utf8'
inf_nan_mode Literal['null', 'constants', 'strings']

How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'.

'constants'
serialize_unknown bool

Attempt to serialize unknown types, str(value) will be used, if that fails "<Unserializable {value_type} object>" will be used.

False
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered, if None a PydanticSerializationError error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False
context Any | None

The context to use for serialization, this is passed to functional serializers as info.context.

None

Raises:

Type Description
PydanticSerializationError

If serialization fails and no fallback function is provided.

Returns:

Type Description
Any

The serialized Python object.