How to pickle and unpickle objects with self-references and from a class with slots?
- by EOL
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]