Skip to content

amisc.serialize

Provides serialization protocols for objects in the package. Serialization in the context of amisc means converting an object to a built-in Python object (e.g. string, dictionary, float, etc.). The serialized objects are then easy to convert to binary or text forms for storage or transmission using various protocols (i.e. pickle, json, yaml, etc.).

Includes:

  • Serializable — mixin interface for serializing and deserializing objects
  • Base64Serializable — mixin class for serializing objects using base64 encoding
  • StringSerializable — mixin class for serializing objects using string representation
  • PickleSerializable — mixin class for serializing objects using pickle files
  • YamlSerializable — metaclass for serializing an object using Yaml load/dump from string

Base64Serializable

Bases: Serializable

Mixin class for serializing objects using base64 encoding.

PickleSerializable

Bases: Serializable

Mixin class for serializing objects using pickle.

Serializable

Bases: ABC

Mixin interface for serializing and deserializing objects.

deserialize(serialized_data) abstractmethod classmethod

Construct a Serializable object from serialized data.

Passing arguments to deserialize

Subclasses should generally not take arguments for deserialization. The serialized object should contain all the information it needs to reconstruct itself. If you need arguments for deserialization, then serialize them along with the object itself and unpack them during the call to deserialize.

Source code in src/amisc/serialize.py
@classmethod
@abstractmethod
def deserialize(cls, serialized_data: _builtin) -> Serializable:
    """Construct a `Serializable` object from serialized data.

    !!! Note "Passing arguments to deserialize"
        Subclasses should generally not take arguments for deserialization. The serialized object should contain
        all the information it needs to reconstruct itself. If you need arguments for deserialization, then
        serialize them along with the object itself and unpack them during the call to deserialize.
    """
    raise NotImplementedError

serialize() abstractmethod

Serialize to a builtin Python object.

Source code in src/amisc/serialize.py
@abstractmethod
def serialize(self) -> _builtin:
    """Serialize to a builtin Python object."""
    raise NotImplementedError

StringSerializable

Bases: Serializable

Mixin class for serializing objects using string representation.

deserialize(serialized_data, trust=False) classmethod

Deserialize a string representation of the object.

Security Risk

Only use trust=True if you trust the source of the serialized data. This provides a more flexible option for eval-ing the serialized data from string. By default, this will instead try to parse the string as a class signature like MyClass(*args, **kwargs).

PARAMETER DESCRIPTION
serialized_data

the string representation of the object

TYPE: str

trust

whether to trust the source of the serialized data (i.e. for eval)

TYPE: bool DEFAULT: False

Source code in src/amisc/serialize.py
@classmethod
def deserialize(cls, serialized_data: str, trust: bool = False) -> StringSerializable:
    """Deserialize a string representation of the object.

    !!! Warning "Security Risk"
        Only use `trust=True` if you trust the source of the serialized data. This provides a more flexible
        option for `eval`-ing the serialized data from string. By default, this will instead try to parse the
        string as a class signature like `MyClass(*args, **kwargs)`.

    :param serialized_data: the string representation of the object
    :param trust: whether to trust the source of the serialized data (i.e. for `eval`)
    """
    if trust:
        return eval(serialized_data)
    else:
        try:
            name, args, kwargs = parse_function_string(serialized_data)
            return cls(*args, **kwargs)
        except Exception as e:
            raise ValueError(f'String "{serialized_data}" is not a valid class signature.') from e

YamlSerializable(obj) dataclass

Bases: Serializable

Mixin for serializing an object using Yaml load/dump from string.