[Tutor] pickling and unpickling custom classes

Lex Flagel flagel at iastate.edu
Tue Oct 28 04:40:45 CET 2008

I'm using a simple class called Hash, which I picked up from the following site:

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)?  From
reading the documentation it seems that classes defined at the top
level of a module can be pickled, but I'm stymied here.  Thanks a


#define Hash
from collections import defaultdict
class Hash(defaultdict):
    def __init__(self):
        defaultdict.__init__(self, Hash)

#build a Hash object
a = Hash()
a[3][4][5] = 6
a['x']['y'] = 'nil'

#now test try to pickle
import pickle
pk = pickle.dumps(a)  #OK
new_a = pickle.loads(pk) #dies!

The pk object won't load, giving this error on my machine:
>>> new_a = pickle.loads(pk) #dies!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python25\lib\pickle.py", line 1374, in loads
    return Unpickler(file).load()
  File "C:\Python25\lib\pickle.py", line 858, in load
  File "C:\Python25\lib\pickle.py", line 1133, in load_reduce
    value = func(*args)
TypeError: __init__() takes exactly 1 argument (2 given)

More information about the Tutor mailing list