Skip to content

Serialize

JSONSerializable

JSON serialization for Python classes. Saves keyword arguments at construction, and also any state returned by the save_state method. Does not attempt to serialize code or any other attributes.

to make class a serializable, subclass JSONSerializable, and in the constructor use e.g. super().__init__(a=0, b=1 ...) with any keyword args which should be serialized.

override save_state and load_state to handle any mutable state.

Constructor args and return values of save_state can be other JSONSerializable objects, or any types which are already serializable by the standard library json module.

Source code in src/anguilla/serialize.py
class JSONSerializable:
    """JSON serialization for Python classes.
    Saves keyword arguments at construction,
    and also any state returned by the `save_state` method.
    Does *not* attempt to serialize code or any other attributes.

    to make class a serializable, subclass JSONSerializable, 
    and in the constructor use e.g. `super().__init__(a=0, b=1 ...)`
    with any keyword args which should be serialized.

    override `save_state` and `load_state` to handle any mutable state.

    Constructor args and return values of `save_state` can be other JSONSerializable objects, or any types which are already serializable by
    the standard library `json` module.
    """
    def __init__(self, **kw):
        self._kw = deepcopy(kw)
        self._kw['__inst__'] = '.'.join((
            self.__class__.__module__,
            self.__class__.__name__))

    def _store(self):
        return {'__state__': self.save_state(), **self._kw}

    def save_state(self):
        """return object state in JSON serializable form"""
        return None

    def load_state(self, state):
        """restore from de-serialized state"""
        pass

load_state(state)

restore from de-serialized state

Source code in src/anguilla/serialize.py
def load_state(self, state):
    """restore from de-serialized state"""
    pass

save_state()

return object state in JSON serializable form

Source code in src/anguilla/serialize.py
def save_state(self):
    """return object state in JSON serializable form"""
    return None

get_cls(s)

convert a type name to a type, importing dependencies as needed

e.g. "somepackage.submodule.SomeClass" -> SomeClass

this works by doing: import somepackage import somepackage.submodule.SomeClass eval("somepackage.submodule.SomeClass")

this should work in most cases, but could possibly break if the package containing the type has a weird structure.

In cases where dependencies rename / reorganize their types, breaking old anguilla files, any translation of type names can be done here.

Source code in src/anguilla/serialize.py
def get_cls(s):
    """convert a type name to a type, importing dependencies as needed

    e.g. "somepackage.submodule.SomeClass" -> SomeClass 

    this works by doing:
    import somepackage
    import somepackage.submodule.SomeClass
    eval("somepackage.submodule.SomeClass")

    this should work in most cases, but could possibly break if the package containing the type has a weird structure.

    In cases where dependencies rename / reorganize their types, breaking old
    anguilla files, any translation of type names can be done here.
    """

    # sanitize inputs
    assert all(item.isidentifier() for item in s.split('.')), s
    parts = s.split('.')

    ### backward compat translations ###
    if parts[0]=='iml': parts[0] = 'anguilla'

    pkg = parts[0]
    mod = '.'.join(parts[:-1])
    # import top level package the type belongs to
    exec(f'import {pkg}') 
    # import submodule the type is in
    exec(f'import {mod}')
    # convert string to type
    return eval(s)