pickle and converting to new-style classes

greg.landrum at gmail.com greg.landrum at gmail.com
Thu Mar 2 22:06:55 CET 2006


Hi,

I have a fairly sizable body of python code that I'm in the process of
modernizing.

One of the modernization steps is converting to use new-style classes,
and this is leading to problems with pickle. What's happening is that
part of the test suite for this code includes pickled instances of the
classes I am modifying, attempting to unpickle these objects is
generating errors in certain cases.

A bit of sample code that shows the same problem:
--------------------
import pickle

# original class definition:
class klass:
  def __init__(self,v):
    self._v=v

# instantiate it:
o = klass(3)
# create a pickle (simulates our saved pickle on disc)
pkl = pickle.dumps(o)

# change the class definition (simulates changing the orginal
# source):
class klass(object):
  def __init__(self,v):
    self._v=v

# this generates an error:
n = pickle.loads(pkl)
--------------------

There error I get is:
Traceback (most recent call last):
  File "newclass.py", line 20, in ?
    n = pickle.loads(pkl)
  File "c:\Python23\Lib\pickle.py", line 1394, in loads
    return Unpickler(file).load()
  File "c:\Python23\Lib\pickle.py", line 872, in load
    dispatch[key](self)
  File "c:\Python23\Lib\pickle.py", line 1084, in load_inst
    self._instantiate(klass, self.marker())
  File "c:\Python23\Lib\pickle.py", line 1074, in _instantiate
    value = klass(*args)
TypeError: in constructor for klass: __init__() takes exactly 2
arguments (1 given)

I realize I'm trying to do something a bit hackish, but re-generating
these pickled instances from scratch would be a rather massive amount
of work, so I'd really like to figure out some way to either
"translate" the pickled instances to work with the new-style class
definitions or to modify the class definition itself so that the
pickles can be loaded (this would be preferable). Is this remotely
possible?

thanks,
-greg




More information about the Python-list mailing list