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.

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.

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.

    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.
    """
    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