reckoner reckoner - 1 year ago 67
Python Question

Pickling an object as an instance of its parent class?

Suppose I had the following subclass that I'm using to temporarily endow

with some extra methods,

class MyList(list):
def some_function(self):

and then I do something like

>>> f = MyList()
>>> .. bunch of list stuff ...
>>> cPickle.dump(f,open('somefile','w'))

Now, that is all well and good until I try to open the file

>>> cPickle.load(open('somefile'))

and I get a complaint that
doesn't exist. Is there a way to somehow
to pickle as a plain
so that when I later try to load
the pickle file, I don't get this missing class error? I would like the pickle file to only refer to the built-in

Answer Source

I think what you wanted to do is to pickle the class instance and bundle up the class description in the pickled object. pickle doesn't pickle a class description, but dill does.

>>> class MyList(list):
...   def some_function(self):
...     pass
>>> f = MyList()
>>> import dill
>>> dill.dump(f, open('somefile','w'))

And then upon loading, it just works...

dude@hilbert>$ python
Python 2.7.12 (default, Jun 29 2016, 12:42:34) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> f = dill.load(open('somefile','r'))
>>> f
>>> type(f)
<class '__main__.MyList'>
>>> g = f.__class__()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download