Short Question

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Short Question

Bach,  Andreas
Hello,

I am trying to run a save/load programm for enthought traits. So the question ist:


What is the easiest way to save and load the traits of HasTraits subclasses to/from a file?


Could anyone help us?


Thanks!


With Regards


Andreas Bach




_______________________________________________
Enthought-Dev mailing list
[hidden email]
https://mail.enthought.com/mailman/listinfo/enthought-dev
Reply | Threaded
Open this post in threaded view
|

Re: Short Question

Gregor Thalhammer

Am 13.03.2014 um 16:01 schrieb Bach, Andreas <[hidden email]>:

Hello,

I am trying to run a save/load programm for enthought traits. So the question ist:

What is the easiest way to save and load the traits of HasTraits subclasses to/from a file?

Could anyone help us?

Thanks!

With Regards

Andreas Bach



Hi Andreas,

I use the following code. For classes derived by HasTraitsPersistent you can save and load the state of all trait attributes during runtime. Essentially it dumps the state obtained by __getstate__ to a file using the pickle module. Trait attributes created with 'transient=True' are not saved, nor are Properties or Delegates or private attributes starting with underscore. Loading the settings issues change notifications. I derive the filename from the value of the settings_id, needs to be modified by subclasses. 

Gregor

--8<------
from traits.api import HasTraits, String
import cPickle as pickle

class HasTraitsPersistent(HasTraits):
    "custom Traits class with methods for loading/saving state"

    settings_id = String('state', transient = True)
    
    def load_settings(self):
        try:
            sfilename = 'config/%s.pkl'%self.settings_id
            with open(sfilename, 'rb') as sfile:
                state = pickle.load(sfile)
                print "load settings", self.settings_id
                self.trait_set(trait_change_notify = True, **state)
        except Exception, e:
            print "error loading settings", 
            print str(self.__class__)
            print e
            print

    def dump_settings(self):
        sfilename = 'config/%s.pkl'%self.settings_id
        with open(sfilename, 'wb') as sfile:
            state = self.__getstate__()
            for key in state.keys():
                if key.startswith('_') and key is not '__traits_version__':
                    state.pop(key)
            pickle.dump(state, sfile)


_______________________________________________
Enthought-Dev mailing list
[hidden email]
https://mail.enthought.com/mailman/listinfo/enthought-dev