pickle and weakref
Nagy László
nagylzs at freemail.hu
Fri Jan 10 08:57:26 EST 2003
I wonder if there is a standard way to pickle/unpickle weak references.
My idea is the following:
import pickle
import weakref
class A:
pass
a = A()
b = A()
c = A()
a.b = b
a.ref_b = weakref.ref(b)
a.ref_c = weakref.ref(c)
data = pickle.dumps(a)
a = pickle.loads(data)
print a # <__main__.A instance at 0X???? >
print a.b # <__main__.A instance at 0X????>
print a.c # None
print a.ref_b # <weakref at 0x???? to 'instance' at 0x????>,
references to pickled instances should be unpickled gracefully
print a.ref_c # <weakref at ????; dead>, references to other (not
pickled) instances should be unpickled as a dead reference
I've already written a wrapper class to do this but it is not a general
solution. My wrapper uses the 'Ownership' concept and
can pickle weak references to instances of a given class only.
This extension should not affect older codes because they don't pickle
any weak references.
What do you think? Is this a good idea?
Laci 1.0
More information about the Python-list
mailing list