aboutsummaryrefslogtreecommitdiffstats
path: root/libmproxy/stateobject.py
blob: 53ccef0e8a41027329a127715923bcd567847f66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from __future__ import absolute_import


class StateObject(object):
    """
        An object with serializable state.

        State attributes can either be serializable types(str, tuple, bool, ...)
        or StateObject instances themselves.
    """
    # An attribute-name -> class-or-type dict containing all attributes that
    # should be serialized. If the attribute is a class, it must implement the
    # StateObject protocol.
    _stateobject_attributes = None
    # A set() of attributes that should be ignored for short state
    _stateobject_long_attributes = frozenset([])

    def from_state(self, state):
        raise NotImplementedError()

    def get_state(self, short=False):
        """
            Retrieve object state. If short is true, return an abbreviated
            format with long data elided.
        """
        state = {}
        for attr, cls in self._stateobject_attributes.iteritems():
            if short and attr in self._stateobject_long_attributes:
                continue
            val = getattr(self, attr)
            if hasattr(val, "get_state"):
                state[attr] = val.get_state(short)
            else:
                state[attr] = val
        return state

    def load_state(self, state):
        """
            Load object state from data returned by a get_state call.
        """
        for attr, cls in self._stateobject_attributes.iteritems():
            if state.get(attr, None) is None:
                setattr(self, attr, None)
            else:
                curr = getattr(self, attr)
                if hasattr(curr, "load_state"):
                    curr.load_state(state[attr])
                elif hasattr(cls, "from_state"):
                    setattr(self, attr, cls.from_state(state[attr]))
                else:
                    setattr(self, attr, cls(state[attr]))