Why derivated exception can not be pickled ?

Dieter Maurer dieter at handshake.de
Wed Sep 5 02:02:12 EDT 2012


Mathieu Courtois <mathieu.courtois at gmail.com> writes:

> Here is my example :
>
>
> import cPickle
>
> ParentClass = object     # works
> ParentClass = Exception  # does not
>
> class MyError(ParentClass):
>     def __init__(self, arg):
>         self.arg = arg
>
>     def __getstate__(self):
>         print '#DBG pass in getstate'
>         odict = self.__dict__.copy()
>         return odict
>
>     def __setstate__(self, state):
>         print '#DBG pass in setstate'
>         self.__dict__.update(state)
>
> exc = MyError('IDMESS')
>
> fo = open('pick.1', 'w')
> cPickle.dump(exc, fo)
> fo.close()
>
> fo = open('pick.1', 'r')
> obj = cPickle.load(fo)
> fo.close()
>
>
> 1. With ParentClass=object, it works as expected.
>
> 2. With ParentClass=Exception, __getstate__/__setstate__ are not called.

The pickle interface is actually more complex and there are several
ways an object can ensure picklability. For example, there is
also a "__reduce__" method. I suppose, that "Exception" defines methods
which trigger the use of an alternative picklability approach (different
from "__getstate__/__setstate__").

I would approach your case the following way: Use "pickle" instead
of "cPickle" and debug picking/unpickling to find out what
happens in detail.




More information about the Python-list mailing list