Skip to content

Instantly share code, notes, and snippets.

@devnull255
Created March 21, 2016 23:37
Show Gist options
  • Save devnull255/434c709d2c4c2b3a8607 to your computer and use it in GitHub Desktop.
Save devnull255/434c709d2c4c2b3a8607 to your computer and use it in GitHub Desktop.
Decorate a class to be persistent, utilizing pyyaml as serializer
import yaml
def persistent(K):
def __repr__(self):
i_vars = dict([(k,self.__dict__[k]) for k in self.__dict__ if not k.startswith('__') and not callable(self.__dict__[k])])
s = "<" + K.__name__ + '('
keywords = []
for i_var in i_vars:
keywords.append("%s=%s" % (i_var,repr(i_vars[i_var])))
s += ','.join(keywords)
s += ')>'
return s
if not hasattr(K,'__repr__'):
K.__repr__ = __repr__
K.__str__ = __repr__
def get_yaml(self):
yamlDict = dict([(k,self.__dict__[k]) for k in self.__dict__ if not k.startswith('__') and not callable(self.__dict__[k])])
yamlText = yaml.dump(yamlDict, default_flow_style=False)
return yamlText
if not hasattr(K,'get_yaml'):
K.get_yaml = get_yaml
def save_yaml(self):
yamlText = self.get_yaml()
if hasattr(self,"name"):
filePath = "%s_%s.yaml" % (self.__class__.__name__,self.name)
else:
filePath = "%s_%d.yaml" % (self.__class__.__name__, self.__hash__())
with open(filePath, 'w') as yamlFile:
yamlFile.write(yamlText)
K.save_yaml = save_yaml
@classmethod
def load_from_file(cls,filePath):
with open(filePath, 'r') as yamlFile:
try:
yamlDict = yaml.load(yamlFile)
return K(**yamlDict)
except Exception, e:
raise
if not hasattr(K,'load_from_file'):
K.load_from_file = load_from_file
return K
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment