[Tutor] pickling and unpickling custom classes
Kent Johnson
kent37 at tds.net
Tue Oct 28 12:29:06 CET 2008
On Mon, Oct 27, 2008 at 11:40 PM, Lex Flagel <flagel at iastate.edu> wrote:
> I'm using a simple class called Hash, which I picked up from the following site:
> http://mail.python.org/pipermail/python-list/2007-August/453716.html
>
> I like using this Hash object for its convenience, but it won't
> unpickle. Is there fix to the code example below (either the pickler
> or the Hash object) that will get it to unpickle (pickle.loads)?
You have to override Hash.__reduce__(), the values returned by
defaultdict.__reduce__() are not correct.
http://docs.python.org/library/pickle.html#pickling-and-unpickling-extension-types
This works. The result of calling __reduce__() is a tuple, hence the
awkward code to build a new value:
class Hash(defaultdict):
def __init__(self):
defaultdict.__init__(self, Hash)
def __reduce__(self):
r = defaultdict.__reduce__(self)
# override __init__ args
return (r[0], (), r[2], r[3], r[4])
Kent
More information about the Tutor
mailing list