API

This part of the documentation lists the full API reference of all public classes and functions.

class serde.Model(*args, **kwargs)[source]

The base model.

to_dict()[source]

Convert this model to a dictionary.

Returns:

the model serialized as a dictionary.

Return type:

OrderedDict

to_json(**kwargs)[source]

Dump the model as a JSON string.

Parameters:

**kwargs – extra keyword arguments to pass directly to json.dumps.

Returns:

a JSON representation of this model.

Return type:

str

classmethod from_dict(d)[source]

Convert a dictionary to an instance of this model.

Parameters:

d (dict) – a serialized version of this model.

Returns:

an instance of this model.

Return type:

Model

classmethod from_json(s, **kwargs)[source]

Load the model from a JSON string.

Parameters:
  • s (str) – the JSON string.

  • **kwargs – extra keyword arguments to pass directly to json.loads.

Returns:

an instance of this model.

Return type:

Model

normalize()[source]

Normalize this model.

Override this method to add any additional normalization to the model. This will be called after all fields have been normalized.

validate()[source]

Validate this model.

Override this method to add any additional validation to the model. This will be called after all fields have been validated.

Fields

This module contains field classes for use with Models.

class serde.fields.Field(rename=None, default=None, serializers=None, deserializers=None, normalizers=None, validators=None)[source]

A field on a Model.

Fields handle serializing, deserializing, normalization, and validation of input values for Model objects.

Parameters:
  • rename (str) – override the name for the field when serializing and expect this name when deserializing.

  • default – a value to use if there is no input field value or the input value is None. This can also be a callable that generates the default. The callable must take no positional arguments. This default only applies to instantiated values. Field values are still required on deserialization.

  • serializers (list) – a list of serializer functions taking the value to serialize as an argument. The functions need to raise an Exception if they fail. These serializer functions will be applied before the primary serializer on this Field.

  • deserializers (list) – a list of deserializer functions taking the value to deserialize as an argument. The functions need to raise an Exception if they fail. These deserializer functions will be applied after the primary deserializer on this Field.

  • normalizers (list) – a list of normalizer functions taking the value to normalize as an argument. The functions need to raise an Exception if they fail. These normalizer functions will be applied after the primary normalizer on this Field.

  • validators (list) – a list of validator functions taking the value to validate as an argument. The functions need to raise an Exception if they fail.

Primitives

class serde.fields.Bool(**kwargs)

This field represents the built-in <class 'bool'> type.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Bytes(**kwargs)

This field represents the built-in <class 'bytes'> type.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Complex(**kwargs)

This field represents the built-in <class 'complex'> type.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Float(**kwargs)

This field represents the built-in <class 'float'> type.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Int(**kwargs)

This field represents the built-in <class 'int'> type.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Str(**kwargs)

This field represents the built-in <class 'str'> type.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Text(encoding=None, errors='strict', **kwargs)[source]

A text field.

A Text is a string field in Python 3 and a unicode field in Python 2. It will normalize byte strings into unicode strings using the given encoding.

Parameters:
  • encoding (str) – the encoding with which to decode bytes. Passed directly to bytes.decode. If not given then chardet.detect will be used to detect the encoding.

  • errors (str) – The error handling scheme to use for the handling of decoding errors. Passed directly to bytes.decode.

  • **kwargs – keyword arguments for the Field constructor.

Containers

In container fields each element is serialized, deserialized, normalized and validated with the specified element type. The element type can be specified using Field classes, Field instances, Model classes, or built-in types that have a corresponding field type in this library.

class serde.fields.Nested(ty, **kwargs)[source]

A field for Model fields.

A Nested is a wrapper field for models to support sub-models. The serialize and deserialize methods call the to_dict() and from_dict() methods on the model class. This allows complex nested models.

Parameters:
  • model_cls (serde.Model) – the nested model class.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Optional(inner=None, **kwargs)[source]

An optional field.

An Optional is a field that is allowed to be None. Serialization, normalization, deserialization, and validation using the wrapped field will only be called if the value is not None.

Parameters:
  • inner – the Field class/instance that this Optional wraps.

  • default – a value to use if there is no input field value or the input value is None. This can also be a callable that generates the default. The callable must take no positional arguments.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Dict(key=None, value=None, **kwargs)[source]

This field represents the built-in dict type.

Parameters:
  • key – the Field class or instance for keys in this Dict.

  • value – the Field class or instance for values in this Dict.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.OrderedDict(key=None, value=None, **kwargs)[source]

An OrderedDict field.

Parameters:
  • key – the Field class or instance for keys in this OrderedDict.

  • value – the Field class or instance for values in this OrderedDict.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.List(element=None, **kwargs)[source]

This field represents the built-in list type.

Parameters:
  • element – the Field class or instance for elements in the List.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Deque(element=None, maxlen=None, **kwargs)[source]

A deque field.

Parameters:
  • element – the Field class or instance for elements in the Deque.

  • maxlen (int) – the maximum length of this Deque.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Set(element=None, **kwargs)[source]

This field represents the built-in set type.

Parameters:
  • element – the Field class or instance for elements in the Set.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.FrozenSet(element=None, **kwargs)[source]

This field represents the built-in frozenset type.

Parameters:
  • element – the Field class or instance for elements in the Set.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Tuple(*elements, **kwargs)[source]

This field represents the built-in tuple type.

Parameters:
  • *elements – the Field classes or instances for elements in this tuple.

  • **kwargs – keyword arguments for the Field constructor.

Standard library

class serde.fields.DateTime(format='iso8601', **kwargs)[source]

A datetime field.

This field serializes datetime objects as strings and deserializes string representations of datetimes as datetime objects.

The date format can be specified. It will default to ISO 8601.

Parameters:
  • format (str) – the datetime format to use. “iso8601” may be used for ISO 8601 datetimes.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Date(format='iso8601', **kwargs)[source]

A date field.

This field behaves in a similar fashion to the DateTime field.

class serde.fields.Time(format='iso8601', **kwargs)[source]

A time field.

This field behaves in a similar fashion to the DateTime field.

class serde.fields.Uuid(output_form='str', **kwargs)[source]

A UUID field.

A Uuid field validates that the input data is a UUID. It serializes the UUID into the specified output form and deserializes hex strings, bytes, fields, or integers as UUIDs.

Parameters:
  • output_form (str) – the type of output form to serialize to. Possible values include ‘str’, ‘urn’, ‘hex’, ‘int’, ‘bytes’, or ‘fields’.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Regex(pattern, flags=0, **kwargs)[source]

A regex field.

A Regex is a string field that validates that data matches a specified regex expression.

Parameters:
  • pattern (str) – the regex pattern that the value must match.

  • flags (int) – the regex flags passed directly to re.compile.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Decimal(resolution=None, **kwargs)[source]

A Decimal field.

This field serializes Decimal objects as strings and deserializes string representations of Decimals as Decimal objects.

The resolution of the decimal can be specified. When not specified, the number is not rounded. When it is specified, the decimal is rounded to this number of decimal places upon serialization and deserialization.

Note: When float type numbers are not rounded before serialization, they will be serialized in exact form, which as they are floats, is almost never the exact intended value, e.g. 0.2 = 0.20000000000000000000023

Parameters:
  • resolution (Union[int, bool]) – The number of decimal places to round to.

  • None (When) –

  • disabled. (rounding is) –

  • **kwargs – keyword arguments for the Field constructor.

Miscellanous

class serde.fields.Choice(choices, **kwargs)[source]

One of a given selection of values.

A Choice field checks if the input data is one of the allowed values. These values do not need to be the same type.

Parameters:
  • choices – a list or range or tuple of allowed values.

  • **kwargs – keyword arguments for the Field constructor.

class serde.fields.Literal(value, **kwargs)[source]

A literal field.

A Literal is a field that always has to be the specified value.

Parameters:
  • value – the value that this Literal wraps.

  • **kwargs – keyword arguments for the Field constructor.

Extended

The following fields are available with the ext feature.

class serde.fields.Domain(**kwargs)

A text field that asserts the text is a valid domain.

The validation is delegated to validators.domain.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Email(**kwargs)

A text field that asserts the text is a valid email.

The validation is delegated to validators.email.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Ipv4Address(**kwargs)

A text field that asserts the text is a valid IPv4 address.

The validation is delegated to validators.ip_address.ipv4.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Ipv6Address(**kwargs)

A text field that asserts the text is a valid IPv6 address.

The validation is delegated to validators.ip_address.ipv6.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.MacAddress(**kwargs)

A text field that asserts the text is a valid MAC address.

The validation is delegated to validators.mac_address.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Slug(**kwargs)

A text field that asserts the text is a valid slug.

The validation is delegated to validators.slug.

Parameters:

**kwargs – keyword arguments for the Field constructor.

class serde.fields.Url(**kwargs)

A text field that asserts the text is a valid URL.

The validation is delegated to validators.url.

Parameters:

**kwargs – keyword arguments for the Field constructor.

Tags

This module contains tag classes for use with Models.

class serde.tags.Tag(recurse=False, serializers=None, deserializers=None)[source]

A tag field for a Model.

Parameters:
  • recurse (bool) – whether to recurse subclasses when calculating model variants.

  • serializers (list) – a list of serializer functions taking the value to serialize as an argument. The functions need to raise an Exception if they fail. These serializer functions will be applied before the primary serializer on this tag.

  • deserializers (list) – a list of deserializer functions taking the value to deserialize as an argument. The functions need to raise an Exception if they fail. These deserializer functions will be applied after the primary deserializer on this tag.

variants()[source]

Returns a list of variants for the bound model class.

lookup_tag(variant)[source]

Get the tag value for the given model variant.

Parameters:

variant (Model) – the model class.

Returns:

the corresponding tag value.

Return type:

str

lookup_variant(tag)[source]

Get the variant for the given tag value.

Parameters:

tag – the tag value.

Returns:

the corresponding Model class.

Return type:

Model

class serde.tags.External(recurse=False, serializers=None, deserializers=None)[source]

A tag to externally tag Model data.

class serde.tags.Internal(tag='tag', **kwargs)[source]

A tag to internally tag Model data.

Parameters:

tag – the key to use when serializing the model variant’s tag.

class serde.tags.Adjacent(tag='tag', content='content', **kwargs)[source]

A tag to adjacently tag Model data.

Parameters:
  • tag – the key to use when serializing the model variant’s tag.

  • content – the key to use when serializing the model variant’s data.

Validators

This module contains validators for use with Fields.

class serde.validators.Validator[source]

An abstract validator class that all validators should subclass.

class serde.validators.Min(endpoint, inclusive=True)[source]

A validator that asserts the value is greater than a minimum.

Parameters:

inclusive (bool) – if this is set to False then the endpoint value will not be considered valid.

class serde.validators.Max(endpoint, inclusive=True)[source]

A validator that asserts the value is less than a maximum.

Parameters:

inclusive (bool) – if this is set to False then the endpoint value will not be considered valid.

class serde.validators.Between(min_endpoint, max_endpoint, inclusive=True)[source]

A validator that asserts the value is between two endpoints.

Parameters:

inclusive (bool) – if this is set to False then the endpoint values will not be considered valid.

class serde.validators.Length(length)[source]

A validator that asserts the value’s length is a specific value.

class serde.validators.LengthMin(endpoint, inclusive=True)[source]

A validator that asserts the value’s length is greater than a minimum.

Parameters:

inclusive (bool) – if this is set to False then the endpoint value will not be considered valid.

class serde.validators.LengthMax(endpoint, inclusive=True)[source]

A validator that asserts the value’s length is less than a maximum.

Parameters:

inclusive (bool) – if this is set to False then the endpoint value will not be considered valid.

class serde.validators.LengthBetween(min_endpoint, max_endpoint, inclusive=True)[source]

A validator that asserts the value’s length is between two endpoints.

Parameters:

inclusive (bool) – if this is set to False then the endpoint values will not be considered valid.

Exceptions

This module contains Exception classes that are used in Serde.

exception serde.exceptions.ContextError[source]

Raised when Fields are used in the wrong context.

exception serde.exceptions.MissingDependencyError[source]

Raised when a dependency is missing.

exception serde.exceptions.ValidationError(message, value=None)[source]

Raised when any Model stage fails.

Parameters:
  • message – a message describing the error that occurred.

  • value – the value which caused this error.