[Python-Dev] Quick-and-dirty weak references

Vladimir Marangozov Vladimir.Marangozov@inrialpes.fr
Wed, 18 Aug 1999 12:42:08 +0100 (NFT)


M.-A. Lemburg wrote:
> 
> Usage is pretty simple:
> 
> from Proxy import WeakProxy
> object = []
> wr = WeakProxy(object)
> wr.append(8)
> del object
> 
> >>> wr[0]
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> mxProxy.LostReferenceError: object already garbage collected
> 
> I have checked the ref counts pretty thoroughly, but before
> going public I would like the Python-Dev crowd to run some
> tests as well: after all, the point is for the weak references
> to be weak and that's sometimes a bit hard to check.

It's even harder to implement them without side effects. I used
the same hack for the __heirs__ class attribute some time ago.
But I knew that a parent class cannot be garbage collected before
all of its descendants. That allowed me to keep weak refs in
the parent class, and preserve the existing strong refs in the
subclasses. On every dealloc of a subclass, the corresponding
weak ref in the parent class' __heirs__ is removed.

In your case, the lifetime of the objects cannot be predicted,
so implementing weak refs by messing with refcounts or checking
mem pointers is a dead end. I don't know whether this is the
case with mxProxy as I just browsed the code quickly, but here's
a scenario where your scheme (or implementation) is not working:

>>> from Proxy import WeakProxy
>>> o = []
>>> p = WeakProxy(o)
>>> d = WeakProxy(o)
>>> p
<WeakProxy object at 20260138>
>>> d
<WeakProxy object at 20261328>
>>> print p
[]
>>> print d
[]
>>> del o
>>> p
<WeakProxy object at 20260138>
>>> d
<WeakProxy object at 20261328>
>>> print p
Illegal instruction (core dumped)


-- 
       Vladimir MARANGOZOV          | Vladimir.Marangozov@inrialpes.fr
http://sirac.inrialpes.fr/~marangoz | tel:(+33-4)76615277 fax:76615252