Last active
December 22, 2015 22:58
-
-
Save pierre-haessig/6543283 to your computer and use it in GitHub Desktop.
Saving and loading Traits in a text file formatusing a minimal amount of formatting and parsing code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''Saving and loading Traits in a text file format | |
using a minimal amount of formatting and parsing code. | |
Pierre Haessig -- September 2013 | |
''' | |
from traits.api import HasTraits, Float | |
class Person(HasTraits): | |
weight = Float(75.0) | |
height = Float(1.80) | |
def save_traits(self, fname): | |
'''save the traits in `fname` | |
Saving is done by writing the repr of the traits dictionnary''' | |
traits_dict = self.get() | |
traits_str = repr(traits_dict) | |
with open(fname, 'w') as out: | |
out.write(traits_str) | |
print("parameters saved to '{}'".format(fname)) | |
def load_traits(self, fname): | |
'''load the traits in `fname` | |
Loading does an eval of the file to retrieve the dictionnary | |
(possible security issue)''' | |
with open(fname) as f: | |
traits_dict = eval(f.readline()) | |
assert type(traits_dict) == dict | |
self.set(**traits_dict) | |
print("parameters loaded: {}".format(str(traits_dict))) | |
joe = Person() | |
joe.save_traits('joe.txt') | |
# Joe gets some fat with age: | |
joe.weight = 100 | |
print('joe is now fat: {}'.format(str(joe.get()))) | |
# Joe goes back in time to retrieve its youth weight: | |
joe.load_traits('joe.txt') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# Pierre Haessig — March 2014 | |
""" A small example to save and restore HasTraits instances with json | |
Related doc: http://docs.enthought.com/traits/traits_user_manual/advanced.html#persistence | |
TODO: add a load_params to dynamically load params into an existing instance | |
""" | |
from traits.api import HasTraits, Float | |
import json | |
class Person(HasTraits): | |
weight = Float(75.0) | |
height = Float(1.80) | |
def save_traits(self, fname): | |
'''save the traits in `fname` (json format) | |
''' | |
with open(fname, 'w') as out: | |
json.dump(self, out, default=_to_json, | |
indent=2, sort_keys=True) | |
print("parameters saved to '{}'".format(fname)) | |
@classmethod | |
def from_params(cls, fname): | |
'''create Person from parameters in `fname` (json format) | |
''' | |
with open(fname) as infile: | |
trait = json.load(infile, object_hook=_from_json) | |
return trait | |
### helpers: | |
def _to_json(py_obj): | |
'''convert `py_obj` to JSON-serializable objects | |
`py_obj` should be an instance of `HasTraits` | |
''' | |
if isinstance(py_obj, HasTraits): | |
py_dict = py_obj.__getstate__() | |
cls_name = py_obj.__class__.__name__ | |
py_dict['__HasTraitsClass__'] = cls_name | |
return py_dict | |
# end _to_json | |
def _from_json(json_object): | |
'''deserializes a HasTraits json object''' | |
cls_dict = { | |
'Person':Person, | |
} | |
if '__HasTraitsClass__' in json_object: | |
cls_name = json_object['__HasTraitsClass__'] | |
cls = cls_dict[cls_name] | |
trait_state = {k:json_object[k] for k in json_object | |
if k != '__HasTraitsClass__'} | |
trait = cls() | |
trait.__setstate__(trait_state) | |
return trait | |
return json_object | |
### Usage | |
joe = Person() | |
print('joe: {:s}'.format(joe.get())) | |
joe.save_traits('joe.json') | |
# Joe gets some fat with age: | |
joe.weight = 100 | |
print('joe is now fat: {:s}'.format(joe.get())) | |
# back in time to retrieve Joe's youth weight: | |
young_joe = Person.from_params('joe.json') | |
print('young joe is back: {:s}'.format(young_joe.get())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment