I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this?
self = cPickle.load(f)
cPickle.dump(self,f,2)
I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this?
self = cPickle.load(f)
cPickle.dump(self,f,2)
If you want to have your class update itself from a saved pickle… you pretty much have to use
__dict__.update
, as you have in your own answer. It's kind of like a cat chasing it's tail, however… as you are asking the instance to essentially "reset" itself with prior state.There's a slight tweak to your answer. You can actually pickle
self
.I used
loads
anddumps
instead ofload
anddump
because I wanted the pickle to save to a string. Usingload
anddump
to a file also works. And, actually, I can usedill
to pickle an class instance to a file, for later use… even if the class is defined interactively. Continuing from above...then stopping and restarting...
I'm using
dill
, which is available here: https://github.com/uqfoundationThe dump part should work as you suggested. for the loading part, you can define a @classmethod that loads an instance from a given file and returns it.
then the caller would do something like:
There is an example of how to pickle an instance here, in the docs. (Search down for the "TextReader" example). The idea is to define
__getstate__
and__setstate__
methods, which allow you to define what data needs to be pickled, and how to use that data to re-instantiate the object.How about writing a class called Serializable that would implement dump and load and make your class inherit from it?
This is what I ended up doing. Updating the
__dict__
means we keep any new member variables I add to the class and just update the ones that were there when the object was last pickle'd. It seems the simplest while maintaining the saving and loading code inside the class itself so calling code just does an object.save().