Skip to content

xtr_serializer

Objects turned into JSON and back, exactly.

A serializer passes a value through a chain of normalizers, which turn objects into plain data, and encoders, which turn plain data into text — and back again. What is read back equals what was written: dataclasses, models, class hierarchies and dates keep their exact types, and a value that cannot make the round trip is refused rather than changed.

JSON_INDENT module-attribute

JSON_INDENT: Final = 'json_indent'

How many spaces each level of nesting is indented by, for JSON a person is to read.

None, as when the key is absent, writes the whole value on one line, for JSON that only a program reads. At most 10: a wider indent makes no text easier to read, and one wide enough to exhaust memory would stop the process rather than fail the call.

NormalizedValue module-attribute

NormalizedValue: TypeAlias = JsonValue

A value made only of what JSON holds: booleans, numbers, strings, lists and objects keyed by strings, nested, and None.

Where the two halves of a serializer meet. Normalizers turn objects into this and back, knowing nothing of formats; encoders turn this into text and back, knowing nothing of classes. Lists and dictionaries only, not any sequence or mapping: each value has a single plain form, so what a tuple or a set becomes, and how it is read back as one, is settled by the normalizer, the step that knows the type it was declared with.

It is pydantic's JsonValue itself, the type the JSON encoder checks data against. The encoder refuses more than the type does, though: NaN and the infinities, which JSON has no form for, and what its parser would not read back. Data passes when it nests no more than about 200 levels deep, holds no integer longer than 4300 characters, its sign included, and no string with a lone surrogate.

ALLOW_EXTRA_ATTRIBUTES module-attribute

ALLOW_EXTRA_ATTRIBUTES: Final = 'allow_extra_attributes'

Whether data may carry fields its type does not declare.

Allowed, they are dropped; refused, reading fails with :class:~xtr_serializer.exception.ExtraAttributesError naming them — so a client hears about a misspelled field instead of having it ignored. When absent, the type's own pydantic configuration decides.

ATTRIBUTES module-attribute

ATTRIBUTES: Final = 'attributes'

The names of the fields to write, as a set; every other field is left out.

Lets one model serve answers that show only part of it. Every field is written when absent.

BY_ALIAS module-attribute

BY_ALIAS: Final = 'by_alias'

Whether fields are written and read under their alias rather than their name.

On when absent: an alias is declared because the data outside spells the field that way, so writing under it and reading it back agree with that data.

COLLECT_DENORMALIZATION_ERRORS module-attribute

COLLECT_DENORMALIZATION_ERRORS: Final = 'collect_denormalization_errors'

The context key asking for every value that does not fit, rather than the first.

On, reading goes on past a value that does not fit its type, then raises one :class:~xtr_serializer.exception.PartialDenormalizationError listing them all instead of a :class:~xtr_serializer.exception.NotNormalizableValueError for the first — so whoever sent the data can be told everything wrong with it at once, not one field per attempt. Off when absent.

FROM_ATTRIBUTES module-attribute

FROM_ATTRIBUTES: Final = 'from_attributes'

Whether reading accepts an object as well as a mapping, taking each field from the object's attribute of the same name.

For turning one object into another — a database row into the model an answer is written from. Off when absent: the data is read as JSON.

IGNORED_ATTRIBUTES module-attribute

IGNORED_ATTRIBUTES: Final = 'ignored_attributes'

The names of fields never to write, as a set.

For a field that must stay out of one answer — a password hash, an internal note — without a second model to leave it out of. No field is left out when absent.

POPULATE_BY_NAME module-attribute

POPULATE_BY_NAME: Final = 'populate_by_name'

Whether reading accepts a field under its own name as well as under its alias.

For data written both by a sender that uses the aliases and by code that uses the names. When absent, the type's own pydantic configuration decides.

SKIP_DEFAULT_VALUES module-attribute

SKIP_DEFAULT_VALUES: Final = 'skip_default_values'

Whether a field holding its default value is left out of what is written.

Keeps the text short when most fields keep their defaults, at the cost of a reader that must know them. Off when absent.

SKIP_NULL_VALUES module-attribute

SKIP_NULL_VALUES: Final = 'skip_null_values'

Whether a field holding None is left out of what is written.

Off when absent, so a reader can tell a field that is empty from one that is missing.

SKIP_UNSET_VALUES module-attribute

SKIP_UNSET_VALUES: Final = 'skip_unset_values'

Whether a field given no value when its object was built is left out of what is written.

What is written is then what the sender said, not the defaults filled in for what it did not — the shape a partial update needs. Off when absent.

STRICT module-attribute

STRICT: Final = 'strict'

Whether reading refuses data that only converts to the declared type, such as "1" for an int, instead of converting it.

For data from a sender that ought to know the types. When absent, the type's own pydantic configuration decides.

Context

Context = Mapping[str, object]

Options for a single call, by name, each read by the step that knows it.

One mapping travels the whole way — serializer, normalizers, encoders — so a call can tune a step it never deals with directly, such as how far the JSON is indented. Each step reads the keys it knows and passes the rest on untouched. That is why values are object: only the step that owns a key knows the type of its value, and it checks what it reads. The context builders put a context together with the type of each value checked where it is set.

SupportedTypes

SupportedTypes = Mapping[type | Literal['*', 'object'], bool | None]

The types a normalizer or a denormalizer handles in one format, as it reports them.

Lets a serializer holding many normalizers find the one for a type without asking each of them about every value. A key names what is handled: a class, which stands for its subclasses too; "object", which stands for every class; or "*", which stands for anything at all, including types that are not classes, such as int | None. Its value says whether that is handled and, if so, what the answer of supports_normalization or supports_denormalization for it depends on:

  • True: on the type and the format alone, so a serializer may ask once per type and remember the answer;
  • False: on the value or the context too, so it asks every time;
  • None: it is not handled.

A type no key covers is not handled. A key naming the type itself is read before any other, so None there settles it; among the keys that cover a type through its subclasses, the first reported counts, so None on a narrower key is passed over when a broader one is reported before it. List the narrower keys first.

ZonedDateTime

ZonedDateTime = Annotated[datetime, PlainSerializer(_write, return_type=str, when_used='json'), PlainValidator(_read, json_schema_input_type=str)]

A datetime in a :class:~zoneinfo.ZoneInfo zone, read back in that zone.

A plain datetime field writes an aware datetime with its offset and reads it back with that offset: the same instant, but the zone's name is gone, and an hour the clocks repeat comes back compared as another time. Annotate the field with this type and it is written as "2026-10-25T03:30:00+02:00[Europe/Bucharest]" — the ISO datetime with its offset, then the zone's name, the form RFC 9557 gives — and read back equal, in the same ZoneInfo, with the same fold. A single string rather than an object, so it stays one JSON value and sorts by its datetime within a zone.

Writing refuses a naive datetime, one with a fixed offset and one whose zone has no name (read from a file) with a :class:~xtr_serializer.NotNormalizableValueError. Reading refuses text not in that form, a zone the zone database lacks, an offset the zone does not have at that time — written under other zone rules than the reader's — and an instant that falls outside the years a datetime holds once shown in the zone, without quoting the text. A datetime subclass, such as a DatePoint, reads back as a datetime.

ContextBuilderInterface

Bases: Protocol

Puts a context together one option at a time, each through a typed method.

A context is a plain mapping: a misspelled key in it, or a value of the wrong type, goes unnoticed until the step that should read it — and a key no step reads goes unnoticed for good. A builder makes each option a method whose name and argument type a type checker knows, and hands back the mapping to pass.

to_dict

to_dict() -> dict[str, object]

Return the context built so far, as a new dictionary to pass to a call.

JsonEncoderContextBuilder

JsonEncoderContextBuilder(context: Context | None = None)

Bases: ContextBuilderTrait

Builds the options the JSON encoder reads, each under its own key.

Each method sets one key and touches no other. Immutable: setting an option returns a new builder and leaves this one as it was, so a builder holding an application's defaults can be extended for one call without that call's options reaching the next. Nothing a caller does to the plain dictionaries, lists, tuples and sets of the context it starts from, or of the one it returns, reaches it; any other value is handed on as it is.

with_indent

with_indent(indent: int | None) -> JsonEncoderContextBuilder

Return a builder that indents each level by indent spaces, or by none.

Sets :data:~xtr_serializer.JSON_INDENT; None writes the value on one line.

PydanticNormalizerContextBuilder

PydanticNormalizerContextBuilder(context: Context | None = None)

Bases: ContextBuilderTrait

Builds the options the pydantic normalizer reads, each under its own key.

Each method sets one key and touches no other, so the options of the other steps can be put in the context it starts from. Immutable: setting an option returns a new builder and leaves this one as it was, so a builder holding an application's defaults can be extended for one call without that call's options reaching the next. Nothing a caller does to the plain dictionaries, lists, tuples and sets of the context it starts from, or of the one it returns, reaches it; any other value is handed on as it is.

context = (
    PydanticNormalizerContextBuilder()
    .with_ignored_attributes({"password_hash"})
    .with_skip_null_values(True)
    .to_dict()
)

with_attributes

with_attributes(attributes: Set[str]) -> PydanticNormalizerContextBuilder

Return a builder that writes only the fields named in attributes.

Sets :data:~xtr_serializer.ATTRIBUTES, to the names as they are now.

with_ignored_attributes

with_ignored_attributes(ignored_attributes: Set[str]) -> PydanticNormalizerContextBuilder

Return a builder that never writes the fields named in ignored_attributes.

Sets :data:~xtr_serializer.IGNORED_ATTRIBUTES, to the names as they are now.

with_skip_null_values

with_skip_null_values(skip_null_values: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether fields holding None are left out.

Sets :data:~xtr_serializer.SKIP_NULL_VALUES.

with_skip_unset_values

with_skip_unset_values(skip_unset_values: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether fields never given a value are left out.

Sets :data:~xtr_serializer.SKIP_UNSET_VALUES.

with_skip_default_values

with_skip_default_values(skip_default_values: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether fields holding their default are left out.

Sets :data:~xtr_serializer.SKIP_DEFAULT_VALUES.

with_by_alias

with_by_alias(by_alias: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether fields are written and read under their alias.

Sets :data:~xtr_serializer.BY_ALIAS.

with_strict

with_strict(strict: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether reading refuses data it would have to convert.

Sets :data:~xtr_serializer.STRICT.

with_allow_extra_attributes

with_allow_extra_attributes(allow_extra_attributes: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether data may carry fields its type does not declare.

Sets :data:~xtr_serializer.ALLOW_EXTRA_ATTRIBUTES.

with_from_attributes

with_from_attributes(from_attributes: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether an object is read through its attributes.

Sets :data:~xtr_serializer.FROM_ATTRIBUTES.

with_populate_by_name

with_populate_by_name(populate_by_name: bool) -> PydanticNormalizerContextBuilder

Return a builder that sets whether a field is read under its name as well as its alias.

Sets :data:~xtr_serializer.POPULATE_BY_NAME.

SerializerContextBuilder

SerializerContextBuilder(context: Context | None = None)

Bases: ContextBuilderTrait

Builds the options that concern a whole call rather than one normalizer or encoder.

Immutable: setting an option returns a new builder and leaves this one as it was, so a builder holding an application's defaults can be extended for one call without that call's options reaching the next. Nothing a caller does to the plain dictionaries, lists, tuples and sets of the context it starts from, or of the one it returns, reaches it; any other value is handed on as it is.

with_collect_denormalization_errors

with_collect_denormalization_errors(collect_denormalization_errors: bool) -> SerializerContextBuilder

Return a builder that sets whether reading reports every value that does not fit.

Sets :data:~xtr_serializer.COLLECT_DENORMALIZATION_ERRORS.

DecoderInterface

Bases: Protocol

Reads text in the formats it supports back into plain data.

The first step of deserializing. A decoder checks only that the text is valid in its format; whether the data fits the type asked for is for the denormalizer to say, so one decoder serves every type.

decode

decode(data: str | bytes, format: str, context: Context | None = None) -> NormalizedValue

Return the plain data data holds.

Parameters:

  • data (str | bytes) –

    Text in format, as a string or as the bytes it arrived in.

  • format (str) –

    The format data is in, one this decoder supports.

  • context (Context | None, default: None ) –

    Options for this call.

Raises:

supports_decoding

supports_decoding(format: str) -> bool

Tell whether this reads format.

EncoderInterface

Bases: Protocol

Writes plain data as text in the formats it supports.

The second step of serializing. An encoder is only ever handed plain data, so it knows its format and no class at all, and one encoder serves every type.

encode

encode(data: NormalizedValue, format: str, context: Context | None = None) -> str

Return data written as text in format.

Parameters:

  • data (NormalizedValue) –

    The plain data to write, as a normalizer returns it.

  • format (str) –

    The format to write it in, one this encoder supports.

  • context (Context | None, default: None ) –

    Options for this call.

Raises:

supports_encoding

supports_encoding(format: str) -> bool

Tell whether this writes format.

JsonEncoder

JsonEncoder(default_context: Context | None = None)

Bases: EncoderInterface, DecoderInterface

Writes plain data as JSON text and reads it back, refusing what JSON cannot carry exactly.

A looser writer puts down NaN as NaN, the key 1 as "1", a tuple as a list, and the data reads back changed. Here pydantic's JSON check refuses those and cycles, and the text written is read once before it is returned, so what would not read back is refused too: nesting deeper than the parser goes, an integer longer than it reads. Reading refuses text that is not JSON, NaN and the infinities included.

Each refusal is a :class:NotEncodableValueError saying what is wrong, never quoting the data. A refusal by the check also says where: the path of keys and indexes leading to the refused value — the keys of a mapping are the data's structure, as the names of attributes are, so they are shown, but not a key that is itself what is refused. A refusal of text that would not read back gives the parser's reason alone: the place the parser names is in text the caller never sees, and how far into it that place is would tell how long the values before it are. Text that is read is refused saying where in it the parser stopped. A call's context wins over the default one.

Keep a copy of default_context, so later changes to it are not picked up.

CircularReferenceError

Bases: SerializerError, RuntimeError

A value contains itself, so it has no plain form to write.

Plain data is a tree: an object reachable from itself — an order holding a line that points back at the order — would never finish being written. It is refused rather than cut short, because a value written with a gap in it reads back as a different value.

Also a :class:RuntimeError: the cycle is in the objects the application built, a mistake to fix in the code, not data from outside to refuse.

ExtraAttributesError

ExtraAttributesError(extra_attributes: tuple[str, ...], *, path: str | None = None, expected_types: tuple[str, ...] = (), current_type: str | None = None, error_type: str | None = None)

Bases: NotNormalizableValueError

Data for an object carried attributes its type does not declare.

Raised when the reading side is set to refuse what it does not know rather than drop it — for data from a client that should hear about a misspelled field instead of having it silently ignored. It is one more value that did not fit, so it is collected with the others when every error is wanted.

The message names the attributes, quoted as the path is, and leaves out what they held.

Attributes:

  • extra_attributes (tuple[str, ...]) –

    The names of the attributes the type does not declare.

Record the attributes the type does not declare, and where the data had them.

Raises:

  • InvalidArgumentError –

    If extra_attributes is empty. No attribute is extra, so there is nothing to refuse; raising this error anyway is a mistake in the code that raises it.

InvalidArgumentError

Bases: SerializerError, ValueError

An argument the serializer was given cannot be used, whatever data comes next.

It is about how the serializer is called or configured, not about what it converts: data that does not fit is an :class:UnexpectedValueError <xtr_serializer.exception.UnexpectedValueError>.

Also a :class:ValueError, so code that already guards what it passes with except ValueError catches it without learning a new exception.

LogicError

Bases: SerializerError, RuntimeError

The serializer was put together or used in a way no input could make right.

A serializer with nothing able to convert the objects it is handed, a class hierarchy registered inconsistently: the data is not to blame, the code is, and the fix belongs in the application rather than in what it was sent.

Also a :class:RuntimeError, because that is what a worker's own error handling already catches.

MappingError

Bases: LogicError

A class hierarchy was registered for serialization in a way that cannot work.

The names registered for the classes of a hierarchy are what lets written data say which class it came from, so they must be unambiguous: one name for two classes, a name on a class outside the hierarchy it is registered in, or a name written under a key that a field also uses would each make some value read back as the wrong class. Raised when the classes are registered, so the mistake shows when the module is imported rather than when the first value fails to come back.

NotEncodableValueError

Bases: UnexpectedValueError

Plain data has no form in the requested format, or text is not valid in it.

The encoder's error, on either side of it: writing a float JSON has no form for, such as infinity, or reading text that is not valid JSON. Raised rather than written approximately, because text that does not say exactly what was meant is read back as something else.

NotNormalizableValueError

NotNormalizableValueError(message: str, *, path: str | None = None, expected_types: tuple[str, ...] = (), current_type: str | None = None, error_type: str | None = None)

Bases: UnexpectedValueError

A value cannot be turned into plain data, or plain data into the type asked for.

Raised on both sides of the conversion: writing a value that has no exact plain form, or reading data that does not fit the declared type — a string where a number belongs, a required field missing. What is read mostly comes from someone else and may hold a password or a token, so the message is put together from the attributes below and nothing else: where the value sits and which types were involved, never the value. The path and the type names are quoted, so a key taken from the data cannot break the message across lines.

Attributes:

  • message (str) –

    What is wrong with the value, in words that do not quote it.

  • path (str | None) –

    Where the value sits in what was being converted, such as "items[0].price"; None for the value as a whole.

  • expected_types (tuple[str, ...]) –

    The names of the types the value could have had.

  • current_type (str | None) –

    The name of the type it had, when known.

  • error_type (str | None) –

    A short code for the kind of problem, such as "missing", for a program to act on; the message leaves it out.

Record what is wrong with the value and where, without the value itself.

PartialDenormalizationError

PartialDenormalizationError(data: object, errors: tuple[NotNormalizableValueError, ...])

Bases: UnexpectedValueError

Data was read to the end, and some of its values did not fit their types.

Raised in place of the first error when the reading side is asked to collect every error, so a form or an API request can be answered with everything that is wrong at once rather than one field per attempt.

The message lists the errors, each by its path and types. The data is never part of it: it is what someone sent, and may hold a secret.

Attributes:

  • data (object) –

    What was being denormalized — for the code handling the error to use, never for the message.

  • errors (tuple[NotNormalizableValueError, ...]) –

    One error for each value that did not fit, each naming its path.

Record the data that was read and every error found in it.

Raises:

  • InvalidArgumentError –

    If errors is empty. Nothing was found, so there is nothing to report; raising this error anyway is a mistake in the code that raises it.

SerializerError

Bases: Exception

Something the serializer could not do — catch this to catch them all.

Serialization happens at the edges of an application: a request body read in, a message written to a queue. One except there has to answer for anything that went wrong, and this is that one; a subclass tells one cause from another — data that does not fit its type, a format nothing reads, a class hierarchy registered wrongly.

No error of this package repeats a value it was handed. What goes through a serializer is often what an application must keep out of its logs — a password, a token, a customer's address — so a message says where the problem is and which types were involved, never what the value was.

That holds only while callers keep the value out of the chain: an error raised from an exception that carries the value puts that value into the traceback, which is rendered whatever the message says. Raise these errors without chaining the input-bearing exception — catch it and raise the error with its typed fields, and no from clause.

UnexpectedValueError

Bases: SerializerError, ValueError

A value, or the data read for one, cannot become what the serializer was asked for.

The family of errors about the data itself, as opposed to how the serializer was set up: text that is not valid in its format, a value with no exact plain form, data that does not fit the type it is read into. Catch it to tell whoever sent the data that it was refused; the subclasses say at which step.

Also a :class:ValueError, the error Python raises for a value of the right type with the wrong content.

UnsupportedFormatError

UnsupportedFormatError(format: str)

Bases: NotEncodableValueError

No encoder or decoder of the serializer handles the requested format.

A value nothing can encode, since nothing encodes that format at all, and typed separately because the fix differs: the data is fine, but the application asked for a format it never set the serializer up for, or misspelled one it did.

The format is quoted in the message, so one taken from a request cannot break the message across lines.

Attributes:

  • format (str) –

    The format that was asked for, such as "json".

Record the format that was asked for.

ClassDiscriminatorMapping dataclass

ClassDiscriminatorMapping(type_property: str, types_mapping: Mapping[str, type] = dict[str, type]())

The key a hierarchy writes class names under, and the classes a declared class takes.

A snapshot: names registered later are not in it, and it cannot be changed. Mappings compare and hash by their key and their names, whatever order the names were given in.

Attributes:

  • type_property (str) –

    The key each value's class name is written under.

  • types_mapping (Mapping[str, type]) –

    Each name a field declaring the class reads, and the class it stands for, in the order the classes were named.

for_class classmethod

for_class(class_: type) -> ClassDiscriminatorMapping | None

Give the mapping of class_ — itself and the subclasses under it that have a name.

None when class_ is in no hierarchy. For the base, that is every name of the hierarchy; for a class under it, the names a field declaring that class reads.

DenormalizerAwareInterface

Bases: Protocol

Accepts, through a setter, the denormalizer that builds the parts of what it builds.

A denormalizer for an object made of other objects builds the object and hands the data for each part back to the serializer's denormalizers, so whichever builds that part's type builds it. Those denormalizers include this one, so the serializer that holds them cannot be a constructor argument: once built, it hands itself to each one that implements this.

set_denormalizer

set_denormalizer(denormalizer: DenormalizerInterface) -> None

Hand the data for nested values to denormalizer from now on.

DenormalizerInterface

Bases: Protocol

Turns plain data back into values of the types it handles.

The last step of deserializing. What it reads came over a wire or out of storage, so it checks the data against the type asked for and refuses what does not fit — saying where, never repeating the value.

denormalize

denormalize(data: object, type_: type[T], format: str | None = None, context: Context | None = None) -> T
denormalize(data: object, type_: object, format: str | None = None, context: Context | None = None) -> object
denormalize(data: object, type_: object, format: str | None = None, context: Context | None = None) -> object

Return a value of type type_ built from data.

Parameters:

  • data (object) –

    The plain data to read, as a decoder returns it.

  • type_ (object) –

    The type to build: a class, and the result is typed as an instance of it, or any other type expression, such as int | None, and the result is typed as object.

  • format (str | None, default: None ) –

    The format data was read from; None when there is none in view.

  • context (Context | None, default: None ) –

    Options for this call, :data:COLLECT_DENORMALIZATION_ERRORS among them.

Raises:

supports_denormalization

supports_denormalization(data: object, type_: object, format: str | None = None, context: Context | None = None) -> bool

Tell whether :meth:denormalize builds type_ from data, read from format.

get_supported_types

get_supported_types(format: str | None) -> SupportedTypes

Return the types this builds from format, and what its answer for them rests on.

Lets a serializer pass over this denormalizer for a type it does not build, and remember its answer for a type whose answer depends on nothing else, instead of calling :meth:supports_denormalization for every value.

NormalizerAwareInterface

Bases: Protocol

Accepts, through a setter, the normalizer that writes the parts of what it writes.

A normalizer for an object made of other objects writes the object and hands each part back to the serializer's normalizers, so whichever handles that part's type writes it. Those normalizers include this one, so the serializer that holds them cannot be a constructor argument: once built, it hands itself to each one that implements this.

set_normalizer

set_normalizer(normalizer: NormalizerInterface) -> None

Hand nested values to normalizer from now on.

NormalizerInterface

Bases: Protocol

Turns values of the types it handles into plain data.

The first step of serializing. A normalizer knows the objects — their fields, the types those were declared with — and nothing of the format the plain data is then written in, so the same normalizer serves every encoder. A serializer holds a list of them, and gives each value to the first that handles it.

normalize

normalize(data: object, format: str | None = None, context: Context | None = None, *, type_: object = None) -> NormalizedValue

Return data as plain data.

What is written, and how it reads back, follows from a type: the one data was declared with when one is given, its own class otherwise. A list or a dict declares nothing about what it holds, nor does a value of a class hierarchy about its base; the declared type does, so that what reads it back as that type gets back what was written.

Parameters:

  • data (object) –

    The value to normalize, one this normalizer handles.

  • format (str | None, default: None ) –

    The format the plain data is to be written in, for a normalizer whose output depends on it; None when there is none in view.

  • context (Context | None, default: None ) –

    Options for this call.

  • type_ (object, default: None ) –

    The type data was declared with, such as list[Item]; None for its own class.

Raises:

  • InvalidArgumentError –

    When data, or type_, is not something this normalizer handles.

  • NotNormalizableValueError –

    When data, or a value inside it, has no exact plain form, or does not fit type_ — and, from a serializer holding several normalizers, when none of them handles it.

  • CircularReferenceError –

    When data contains itself.

supports_normalization

supports_normalization(data: object, format: str | None = None, context: Context | None = None, *, type_: object = None) -> bool

Tell whether :meth:normalize handles data, declared as type_, in format.

get_supported_types

get_supported_types(format: str | None) -> SupportedTypes

Return the types this handles in format, and what its answer for them rests on.

Lets a serializer pass over this normalizer for a type it does not handle, and remember its answer for a type whose answer depends on nothing else, instead of calling :meth:supports_normalization for every value.

PydanticNormalizer

PydanticNormalizer(default_context: Context | None = None)

Bases: NormalizerInterface, DenormalizerInterface

Turns any value pydantic has a schema for into plain data, and plain data back into it.

pydantic converts; this maps the context (a call's over the default one, also handed to validators as info.context) onto pydantic's options, and pydantic's errors onto this package's, with paths and never values. A validator's message is passed on as worded; what other code raises as data is read, such as a key of the data comparing itself, is refused naming only the class of what it raised. Threads may share a normalizer; a type whose comparison waits for another thread, or uses another normalizer, can deadlock them.

Each type is strict, finite, with bytes as base64 and durations in ISO 8601, and a plain datetime in it takes an aware datetime only. A model, or a dataclass pydantic built, keeps its own configuration and rules instead, down to the next type with one of its own, wherever it sits: a model that is to be exact declares those settings itself, and types its datetimes AwareDatetime. The :data:~xtr_serializer.STRICT key overrides strictness for every type.

What is written is checked as the JSON encoder checks it, so a float NaN or infinity a model's own configuration allows is refused all the same. It is then read back under the same context and refused unless every part comes back equal and of the same type — a decimal NaN, a set, tuple or model in a field declaring no type, True or an enum member in an int field would not; a DatePoint reads back as the datetime declared. A partial write is checked but not read back. A plain datetime field keeps the offset of a zone but not its name; :data:~xtr_serializer.ZonedDateTime keeps both. Data is read as JSON, which is where strict pydantic takes a date, a UUID, a tuple or an enum from text or a list.

A value of a class hierarchy (see :func:~xtr_serializer.discriminator_map) is written with its class's name and read back as that class, wherever its base or a class under it is declared.

A value is written as the type it is declared with, when one is given, and as its own class otherwise. A list or a dict on its own declares nothing about what it holds, so it is written only when all it holds reads back as itself — plain JSON — unless its type is declared, such as list[Item]; a value of a class no schema is built for, by the annotation it is declared with, such as one carrying pydantic's PlainSerializer and PlainValidator.

The bytes in a named tuple inside a typed dict with a configuration of its own — and, before pydantic 2.14, inside a model or a dataclass with one — are written as base64 whatever that configuration says, yet read as it says: unless it says base64 too, a value holding them would read back changed, so it is refused.

Keep a copy of default_context, so later changes to it are not picked up.

Serializer

Serializer(normalizers: Sequence[NormalizerInterface | DenormalizerInterface] = (), encoders: Sequence[EncoderInterface | DecoderInterface] = (), default_context: Context | None = None)

Bases: SerializerInterface, NormalizerInterface, DenormalizerInterface, EncoderInterface, DecoderInterface

Writes values as text, and reads text back, through the normalizers and encoders it holds.

Serializing normalizes the value, then encodes the plain data; deserializing decodes the text, then denormalizes the data into the type asked for. Each step goes to the first normalizer or encoder, in the order given, that handles it. The serializer hands itself to each that asks, through set_serializer, set_normalizer or set_denormalizer, for nested values.

A call's context wins over the default one key by key. A format nothing encodes is refused before anything is normalized. None, booleans, integers, floats and strings are written as they are, unless a type is declared for them. A list or a dict is not looked into: it goes to a normalizer like any value, and the pydantic normalizer writes it only when it holds plain JSON or its type is declared (type_). Which normalizer handles a type is remembered as its get_supported_types allows. Threads may share a serializer.

Hold normalizers and encoders, each in priority order, and hand itself to them.

Raises:

  • InvalidArgumentError –

    When a normalizer neither normalizes nor denormalizes, or an encoder neither encodes nor decodes.

SerializerAwareInterface

Bases: Protocol

Accepts the serializer it is part of, through a setter.

For a normalizer or an encoder that needs the whole serializer for part of its work — one that embeds a value already written as text, say. The serializer cannot be a constructor argument: it is built from its normalizers and encoders, so it does not exist yet when they do. Once built, the serializer hands itself to each one that implements this.

set_serializer

set_serializer(serializer: SerializerInterface) -> None

Use serializer, the one this is part of, from now on.

SerializerInterface

Bases: Protocol

Writes a value as text in a format, and reads such text back into the type asked for.

What an application depends on to put values on a wire or in storage and take them back. Behind it, a normalizer turns the value into plain data and an encoder writes that data in the format; reading takes the same steps the other way. What is read back equals what was written: a value that could not make the round trip exactly is refused when it is written, rather than changed.

serialize

serialize(data: object, format: str, context: Context | None = None, *, type_: object = None) -> str

Return data written as text in format.

What is written follows from the type data is declared with, its own class unless type_ says otherwise; reading the text back into that same type gives back data.

Parameters:

  • data (object) –

    The value to write.

  • format (str) –

    The format to write it in, such as "json".

  • context (Context | None, default: None ) –

    Options for this call, each read by the step it concerns.

  • type_ (object, default: None ) –

    The type data is declared with, the one it is to be read back into: a list or a dict declares nothing about what it holds, list[Item] does; and the base of a class hierarchy may be declared for a value of a class under it. None for its own class.

Raises:

deserialize

deserialize(data: str | bytes, type_: type[T], format: str, context: Context | None = None) -> T
deserialize(data: str | bytes, type_: object, format: str, context: Context | None = None) -> object
deserialize(data: str | bytes, type_: object, format: str, context: Context | None = None) -> object

Return the value of type type_ that data, text in format, holds.

Parameters:

  • data (str | bytes) –

    Text in format, as a string or as the bytes it arrived in.

  • type_ (object) –

    The type to read into: a class, and the result is typed as an instance of it, or any other type expression, such as int | None, and the result is typed as object.

  • format (str) –

    The format data is in, such as "json".

  • context (Context | None, default: None ) –

    Options for this call, each read by the step it concerns.

Raises: