2014-03-10 21:36:47 +00:00
|
|
|
from __future__ import absolute_import
|
2016-02-08 03:19:25 +00:00
|
|
|
from netlib.utils import Serializable
|
2014-03-10 21:36:47 +00:00
|
|
|
|
2014-09-16 21:54:17 +00:00
|
|
|
|
2016-02-08 03:19:25 +00:00
|
|
|
class StateObject(Serializable):
|
2016-02-14 13:43:48 +00:00
|
|
|
|
2014-01-31 00:06:35 +00:00
|
|
|
"""
|
2016-02-08 03:19:25 +00:00
|
|
|
An object with serializable state.
|
2014-01-31 00:06:35 +00:00
|
|
|
|
2016-02-08 03:19:25 +00:00
|
|
|
State attributes can either be serializable types(str, tuple, bool, ...)
|
|
|
|
or StateObject instances themselves.
|
2014-01-31 00:06:35 +00:00
|
|
|
"""
|
|
|
|
|
2016-02-08 03:19:25 +00:00
|
|
|
_stateobject_attributes = None
|
|
|
|
"""
|
|
|
|
An attribute-name -> class-or-type dict containing all attributes that
|
|
|
|
should be serialized. If the attribute is a class, it must implement the
|
|
|
|
Serializable protocol.
|
|
|
|
"""
|
2014-01-31 00:06:35 +00:00
|
|
|
|
2016-02-08 01:10:10 +00:00
|
|
|
def get_state(self):
|
2014-09-17 01:58:56 +00:00
|
|
|
"""
|
2016-02-08 03:19:25 +00:00
|
|
|
Retrieve object state.
|
2014-09-17 01:58:56 +00:00
|
|
|
"""
|
2014-09-16 23:35:14 +00:00
|
|
|
state = {}
|
|
|
|
for attr, cls in self._stateobject_attributes.iteritems():
|
2014-09-17 01:58:56 +00:00
|
|
|
val = getattr(self, attr)
|
|
|
|
if hasattr(val, "get_state"):
|
2016-02-08 01:10:10 +00:00
|
|
|
state[attr] = val.get_state()
|
2014-09-17 01:58:56 +00:00
|
|
|
else:
|
|
|
|
state[attr] = val
|
2014-09-16 23:35:14 +00:00
|
|
|
return state
|
2014-09-16 21:54:17 +00:00
|
|
|
|
2016-02-08 03:19:25 +00:00
|
|
|
def set_state(self, state):
|
2014-09-17 01:58:56 +00:00
|
|
|
"""
|
2016-02-08 03:19:25 +00:00
|
|
|
Load object state from data returned by a get_state call.
|
2014-09-17 01:58:56 +00:00
|
|
|
"""
|
2016-02-08 03:19:25 +00:00
|
|
|
state = state.copy()
|
2014-09-16 23:35:14 +00:00
|
|
|
for attr, cls in self._stateobject_attributes.iteritems():
|
2016-02-08 03:19:25 +00:00
|
|
|
if state.get(attr) is None:
|
|
|
|
setattr(self, attr, state.pop(attr))
|
2014-09-16 23:35:14 +00:00
|
|
|
else:
|
|
|
|
curr = getattr(self, attr)
|
2016-02-08 03:19:25 +00:00
|
|
|
if hasattr(curr, "set_state"):
|
|
|
|
curr.set_state(state.pop(attr))
|
2014-09-16 23:35:14 +00:00
|
|
|
elif hasattr(cls, "from_state"):
|
2016-02-08 03:19:25 +00:00
|
|
|
obj = cls.from_state(state.pop(attr))
|
|
|
|
setattr(self, attr, obj)
|
|
|
|
else: # primitive types such as int, str, ...
|
|
|
|
setattr(self, attr, cls(state.pop(attr)))
|
|
|
|
if state:
|
|
|
|
raise RuntimeWarning("Unexpected State in __setstate__: {}".format(state))
|