Skip to content

Commit

Permalink
Optionally store properties with json method
Browse files Browse the repository at this point in the history
  • Loading branch information
rgerkin committed Dec 6, 2017
1 parent 7c7dbe9 commit 5467d6c
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions sciunit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def __getstate__(self):
del state[key]
return state

def _state(self, state=None, keys=None, exclude=None):
def _state(self, state=None, keys=[], exclude=[]):
if state is None:
state = self.__getstate__()
if keys:
Expand All @@ -103,6 +103,17 @@ def _state(self, state=None, keys=None, exclude=None):
state = {key:state[key] for key in state.keys() if key not in exclude}
return state

def _properties(self, keys=[], exclude=[]):
result = {}
props = [p for p in dir(self.__class__) \
if isinstance(getattr(self.__class__,p),property)]
exclude += ['state','hash','id']
for prop in props:
if prop not in exclude:
if not keys or prop in keys:
result[prop] = getattr(self,prop)
return result

@property
def state(self):
return self._state()
Expand All @@ -112,16 +123,23 @@ def hash(self):
"""A unique numeric identifier of the current model state"""
return dict_hash(self.state)

@property
def json(self):
def json(self, add_props=False, keys=[], exclude=[]):
def serialize(obj):
try:
s = json.dumps(obj)
except:
s = json.dumps(obj.state, default=serialize)
except TypeError:
state = obj.state
if add_props:
state.update(obj._properties())
state = self._state(state=state, keys=keys, exclude=exclude)
s = json.dumps(state, default=serialize)
return json.loads(s)
return serialize(self)

@property
def _class(self):
return self.__class__.__name__

@property
def id(self):
return str(self.json)
Expand Down

0 comments on commit 5467d6c

Please sign in to comment.