attr_utils.serialise

Add serialisation and deserialisation capability to attrs classes.

Based on attrs-serde.

Example usage

>>> import attr
>>> from attr_utils.serialise import serde

>>> person_dict = {"contact": {"personal": {"name": "John"}, "phone": "555-112233"}}

>>> name_path = ["contact", "personal", "name"]
>>> phone_path = ["contact", "phone"]

>>> @serde
... @attr.s
... class Person(object):
...     name = attr.ib(metadata={"to": name_path, "from": name_path})
...     phone = attr.ib(metadata={"to": phone_path, "from": phone_path})

>>> p = Person.from_dict(person_dict)
Person(name=John phone=555-112233)

>>> p.to_dict
{"contact": {"personal": {"name": "John"}, "phone": "555-112233"}}

API Reference

serde(cls=None, from_key='from', to_key='to')[source]

Decorator to add serialisation and deserialisation capabilities to attrs classes.

The keys used in the dictionary output, and used when creating the class from a dictionary, can be controlled using the metadata argument in attr.ib():

from attr_utils.serialize import serde
import attr

@serde
@attr.s
class Person(object):
    name = attr.ib(metadata={"to": name_path, "from": name_path})
    phone = attr.ib(metadata={"to": phone_path, "from": phone_path})

The names of the keys given in the metadata argument can be controlled with the from_key and to_key arguments:

from attr_utils.serialize import serde
import attr

@serde(from_key="get", to_key="set")
@attr.s
class Person(object):
    name = attr.ib(metadata={"get": name_path, "set": name_path})
    phone = attr.ib(metadata={"get": phone_path, "set": phone_path})

This may be required when using other extensions to attrs.

Parameters
  • cls (Optional[Type[AttrsClass]]) – The attrs class to add the methods to. Default None.

  • from_key (str) – Default 'from'.

  • to_key (str) – Default 'to'.

Return type

Union[Type[AttrsClass], Callable[[Type[AttrsClass]], Type[AttrsClass]]]

Overloads

Classes decorated with @serde will have two new methods added:

classmethod from_dict(d)

Construct an instance of the class from a dictionary.

Parameters

d (Mapping[str, Any]) – The dictionary.

to_dict(convert_values=False):

Returns a dictionary containing the contents of the class.

Parameters

convert_values (bool) – Recurse into other attrs classes, and convert tuples, sets etc. into lists. This may be required to later construct a new class from the dictionary if the class uses complex converter functions.

Return type

MutableMapping[str, Any]

Changed in version 0.5.0: By default values are left unchanged. In version 0.4.0 these were converted to basic Python types, which may be undesirable. The original behaviour can be restored using the convert_values parameter.