[Python-3000] weakrefs and cyclic references
tomer filiba
tomerfiliba at gmail.com
Wed May 31 20:02:19 CEST 2006
the current gc already detects cyclic referencing between objects,
and by what i understood, it can free the memory the objects take,
but __del__ is never call because there's not telling where to
start the __del__ chain.
by cyclic referencing i mean something like
>>> class x(object):
... def __init__(self):
... self.next = self
... def __del__(self):
... print "deleted"
...
>>> y=x()
>>> del y
>>> import gc
>>> gc.collect()
2
while __del__ was never called. you can solve the problem using
weakref.proxy, in a fashion like
>>> class x(object):
... def __init__(self):
... self.next = weakref.proxy(self)
... def __del__(self):
... print "deleted", repr(self.next)
...
>>> y=x()
>>> y
<__main__.x object at 0x00B9E190>
>>> y.next
<weakproxy at 00ADFF60 to x at 00B9E190>
>>> y.next.next
<weakproxy at 00ADFF60 to x at 00B9E190>
>>> del y
deleted <weakproxy at 00ADFF60 to NoneType at 1E1A1E00>
so why not do this automatically?
this idea is to simplify the GC and completely avoid cyclic references
between objects. it's quite simple: every time an assignment is made, i.e.,
self.next = self
the interpreter would automatically detect the assignment would create
a cyclic reference, and would instead create a weakproxy instead, i.e.
self.next = self ==> self.next = weakref.proxy(self)
this approach has several benefits:
* the object stays alive only when *external* references to it exist
* makes the GC a lot simpler (only refcounts are needed)
* __del__ is always called
* the only problem is when __del__ is called, some attributes might
refer to None, but that can be easily anticipated by the code of the
destructor
i guess it has a performance penalty... but maybe there can be a
trick around it. i can imagine the code of the INCREF() detecting
the assignment yields an increment of two instead of one, and
would therefore create a weakref. of coure this optimization is
too lax, but something in that direction.
-tomer
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20060531/cec30cc5/attachment.htm
More information about the Python-3000
mailing list