pickle and converting to new-style classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • greg.landrum@gmail.com

    #1

    pickle and converting to new-style classes

    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(pk l)
    --------------------

    There error I get is:
    Traceback (most recent call last):
    File "newclass.p y", line 20, in ?
    n = pickle.loads(pk l)
    File "c:\Python23\Li b\pickle.py", line 1394, in loads
    return Unpickler(file) .load()
    File "c:\Python23\Li b\pickle.py", line 872, in load
    dispatch[key](self)
    File "c:\Python23\Li b\pickle.py", line 1084, in load_inst
    self._instantia te(klass, self.marker())
    File "c:\Python23\Li b\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

Working...