pickling a subclass of tuple

fedor nobody at here.com
Sat Jan 1 07:01:50 EST 2005


Hi all, happy new year,

I was trying to pickle a instance of a subclass of a tuple when I ran 
into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should 
I rewrite my class so I can pickle it?

Thanks ,

Fedor

#!/usr/bin/env python
import pickle
class A(tuple):
     def __new__(klass, arg1,arg2):
         return super(A,klass).__new__(klass, (arg1,arg2))
a=A(1,2)
print "no pickle",a
print "normal pickle",pickle.loads(pickle.dumps(a))
print "highest protocol", 
pickle.loads(pickle.dumps(a,pickle.HIGHEST_PROTOCOL))

This is the output:
'''
no pickle (1, 2)
normal pickle (1, 2)
highest protocol
Traceback (most recent call last):
   File "./test.py", line 9, in ?
     print "highest 
protocol",pickle.loads(pickle.dumps(a,pickle.HIGHEST_PROTOCOL))
   File "/usr/lib/python2.3/pickle.py", line 1394, in loads
     return Unpickler(file).load()
   File "/usr/lib/python2.3/pickle.py", line 872, in load
     dispatch[key](self)
   File "/usr/lib/python2.3/pickle.py", line 1097, in load_newobj
     obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 3 arguments (2 given)
'''



	



More information about the Python-list mailing list