How to pickle and unpickle objects with self-references and from a class with slots?

Posted by EOL on Stack Overflow See other posts from Stack Overflow or by EOL
Published on 2010-05-27T15:48:30Z Indexed on 2010/05/27 15:51 UTC
Read the original article Hit count: 164

Filed under:
|
|
|
|

Is it possible to pickle an object from a class with slots, when this object references itself through one of its attributes? Here is a simple example:

import weakref
import pickle

class my_class(object):

    __slots__ = ('an_int', 'ref_to_self', '__weakref__')

    def __init__(self):
        self.an_int = 42
        self.ref_to_self = weakref.WeakKeyDictionary({self: 1})

    # __getstate__ and __setstate__ not defined: how should this be done?

if __name__ == '__main__':

    obj = my_class()

    # How to make the following work?
    obj_pickled = pickle.dumps(obj)
    obj_unpickled = pickle.loads(obj_pickled)

    # Self-references should be kept:
    print "OK?", obj_unpickled == obj_unpickled.ref_to_self.keys()[0]

© Stack Overflow or respective owner

Related posts about python

Related posts about pickle