Skip to content

pydantic_core

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.

Attributes

title

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

Type: str

Methods

validate_python

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.

Returns

Any — The validated object.

Parameters

input : Any

The Python object to validate.

strict : bool | None Default: None

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.

from_attributes : bool | None Default: None

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

context : Any | None Default: None

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

self_instance : Any | None Default: None

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

allow_partial : bool | Literal[‘off’, ‘on’, ‘trailing-strings’] Default: False

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.

by_alias : bool | None Default: None

Whether to use the field’s alias when validating against the provided input data.

by_name : bool | None Default: None

Whether to use the field’s name when validating against the provided input data.

Raises
  • ValidationError — If validation fails.
  • Exception — Other error types maybe raised if internal errors occur.

isinstance_python

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.

Returns

boolTrue if validation succeeds, False if validation fails.

validate_json

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.

Returns

Any — The validated Python object.

Parameters

input : str | bytes | bytearray

The JSON data to validate.

strict : bool | None Default: None

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.

context : Any | None Default: None

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

self_instance : Any | None Default: None

An instance of a model set attributes on from validation.

allow_partial : bool | Literal[‘off’, ‘on’, ‘trailing-strings’] Default: False

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.

by_alias : bool | None Default: None

Whether to use the field’s alias when validating against the provided input data.

by_name : bool | None Default: None

Whether to use the field’s name when validating against the provided input data.

Raises
  • ValidationError — If validation fails or if the JSON data is invalid.
  • Exception — Other error types maybe raised if internal errors occur.

validate_strings

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.

Returns

Any — The validated Python object.

Parameters

input : _StringInput

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

strict : bool | None Default: None

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.

context : Any | None Default: None

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

allow_partial : bool | Literal[‘off’, ‘on’, ‘trailing-strings’] Default: False

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.

by_alias : bool | None Default: None

Whether to use the field’s alias when validating against the provided input data.

by_name : bool | None Default: None

Whether to use the field’s name when validating against the provided input data.

Raises
  • ValidationError — If validation fails or if the JSON data is invalid.
  • Exception — Other error types maybe raised if internal errors occur.

validate_assignment

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.

Returns

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)

Parameters

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.

strict : bool | None Default: None

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.

from_attributes : bool | None Default: None

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

context : Any | None Default: None

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

by_alias : bool | None Default: None

Whether to use the field’s alias when validating against the provided input data.

by_name : bool | None Default: None

Whether to use the field’s name when validating against the provided input data.

Raises
  • ValidationError — If validation fails.
  • Exception — Other error types maybe raised if internal errors occur.

get_default_value

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.

Returns

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

Parameters

strict : bool | None Default: None

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.

Raises
  • ValidationError — If validation fails.
  • Exception — Other error types maybe raised if internal errors occur.

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.

Methods

to_python

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.

Returns

Any — The serialized Python object.

Parameters

value : Any

The Python object to serialize.

mode : str | None Default: 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.

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 | None Default: None

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.

warnings : bool | Literal[‘none’, ‘warn’, ‘error’] Default: True

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

fallback : Callable[[Any], Any] | None Default: None

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.

context : Any | None Default: None

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

Raises
  • PydanticSerializationError — If serialization fails and no fallback function is provided.

to_json

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.

Returns

bytes — JSON bytes.

Parameters

value : Any

The Python object to serialize.

indent : int | None Default: None

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 | None Default: None

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.

warnings : bool | Literal[‘none’, ‘warn’, ‘error’] Default: True

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

fallback : Callable[[Any], Any] | None Default: None

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.

context : Any | None Default: None

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

Raises
  • PydanticSerializationError — If serialization fails and no fallback function is provided.

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.

Attributes

title

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

Type: str

Methods

from_exception_data

@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.

Returns

Self

Parameters

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.

error_count

def error_count() -> int
Returns

int — The number of errors in the validation error.

errors

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

Details about each error in the validation error.

Returns

list[ErrorDetails] — A list of ErrorDetails for each error in the validation error.

Parameters

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.

json

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.

Returns

str — a JSON string.

Parameters

indent : int | None Default: None

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.

ErrorDetails

Bases: _TypedDict

Attributes

type

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

loc

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

Type: tuple[int | str, …]

msg

A human readable error message.

Type: str

input

The input data at this loc that caused the error.

Type: _Any

ctx

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

url

The documentation URL giving information about the error. No URL is available if a PydanticCustomError is used.

Type: _NotRequired[str]

InitErrorDetails

Bases: _TypedDict

Attributes

type

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

Type: str | PydanticCustomError

loc

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

Type: _NotRequired[tuple[int | str, …]]

input

The input data at this loc that caused the error.

Type: _Any

ctx

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

SchemaError

Bases: Exception

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

Methods

error_count

def error_count() -> int
Returns

int — The number of errors in the schema.

errors

def errors() -> list[ErrorDetails]
Returns

list[ErrorDetails] — A list of ErrorDetails for each error in the schema.

PydanticCustomError

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.

Constructor Parameters

error_type : LiteralString

The error type.

message_template : LiteralString

The message template.

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

The data to inject into the message template.

Attributes

context

Values which are required to render the error message, and could hence be useful in passing error data forward.

Type: dict[str, Any] | None

type

The error type associated with the error. For consistency with Pydantic, this is typically a snake_case string.

Type: str

message_template

The message template associated with the error. This is a string that can be formatted with context variables in \{curly_braces\}.

Type: str

Methods

message

def message() -> str

The formatted message associated with the error. This presents as the message template with context variables appropriately injected.

Returns

str

PydanticKnownError

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.

Constructor Parameters

error_type : ErrorType

The error type.

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

The data to inject into the message template.

Attributes

context

Values which are required to render the error message, and could hence be useful in passing error data forward.

Type: dict[str, Any] | None

type

The type of the error.

Type: ErrorType

message_template

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

Methods

message

def message() -> str

The formatted message associated with the error. This presents as the message template with context variables appropriately injected.

Returns

str

PydanticOmit

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.

PydanticUseDefault

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.

PydanticSerializationError

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.

Constructor Parameters

message : str

The message associated with the error.

PydanticSerializationUnexpectedValue

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.

Constructor Parameters

message : str

The message associated with the unexpected value.

Url

Bases: SupportsAllComparisons

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

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.

MultiHostHost

Bases: _TypedDict

A host part of a multi-host URL.

Attributes

username

The username part of this host, or None.

Type: str | None

password

The password part of this host, or None.

Type: str | None

host

The host part of this host, or None.

Type: str | None

port

The port part of this host, or None.

Type: int | None

ArgsKwargs

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.

Attributes

args

The arguments (inherently ordered) for a function call.

Type: tuple[Any, …]

kwargs

The keyword arguments for a function call.

Type: dict[str, Any] | None

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.

Attributes

value

Returns the value wrapped by Some.

Type: _T

TzInfo

Bases: tzinfo

An pydantic-core implementation of the abstract datetime.tzinfo class.

Methods

tzname

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.

Returns

str | None

utcoffset

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.

Returns

datetime.timedelta | None

dst

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.

Returns

datetime.timedelta | None

fromutc

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.

Returns

datetime.datetime

ErrorTypeInfo

Bases: _TypedDict

Gives information about errors.

Attributes

type

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

Type: ErrorType

message_template_python

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

Type: str

example_message_python

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

Type: str

message_template_json

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

Type: _NotRequired[str]

example_message_json

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

Type: _NotRequired[str]

example_context

Example of context values.

Type: dict[str, _Any] | None

to_json

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.

Returns

bytes — JSON bytes.

Parameters

value : Any

The Python object to serialize.

indent : int | None Default: None

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.

fallback : Callable[[Any], Any] | None Default: None

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.

context : Any | None Default: None

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

Raises

  • PydanticSerializationError — If serialization fails and no fallback function is provided.

from_json

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.

Returns

Any — The deserialized Python object.

Parameters

data : str | bytes | bytearray

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.

cache_strings : bool | Literal[‘all’, ‘keys’, ‘none’] Default: True

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.

allow_partial : bool | Literal[‘off’, ‘on’, ‘trailing-strings’] Default: False

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.

Raises

  • ValueError — If deserialization fails.

to_jsonable_python

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

Returns

Any — The serialized Python object.

Parameters

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.

fallback : Callable[[Any], Any] | None Default: None

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.

context : Any | None Default: None

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

Raises

  • PydanticSerializationError — If serialization fails and no fallback function is provided.

__version__

Type: str