reckoner reckoner - 1 month ago 9
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

list
with some extra methods,

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


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
MyList
doesn't exist. Is there a way to somehow
get
MyList
to pickle as a plain
list
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
list
type.

Answer

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__()