problem with weakref.proxy

Jp Calderone exarkun at intarweb.us
Sat Jan 31 09:18:31 EST 2004


On Sat, Jan 31, 2004 at 02:52:45PM +0100, Walter Haslbeck wrote:
> Hello,
> 
> I'm a completly Python newbie. As a first learning project I want to port
> an game-engine I have writte some time ago in pure C to Python using OO
> methods.
> 
> So I created a base-class 'GOb' (GameObject). This class should have
> a sorted list of all instances stored as as class-attribte __olist[].
> 
> When I add a reference of the new created object in the constructor
> (with GOb.__olist.append(self)) I have 2 references to each created
> instance and if I 'del' the instance the destructor is not called,
> because __olist[] holds another reference to that object.
> 
> Now I got to tip to use the weakref module. Well I thought this should
> be exactly what I need and changed the program to add not a reference
> to the instances but a weakref.proxy.
> 
> So now my instances are deleted really deleted when I use 'del', but:
> How do get corresponding weakref.proxy object out of __olist[]?
> 
> I tried to use the callback parameter from weakref.proxy, but at the
> time when the callback takes place, the proxy object is allready 'dead',
> I get an Exception when I try to remove the proxy-instance from __olist[]:

  A WeakKeyDictionary or WeakValueDictionary might be a better fit for your
problem.  There is no need for you to remove the object from these manually. 
When the object is no longer referenced anywhere else, it also no longer
belongs to the dictionary.

    >>> class foo: pass
    ... 
    >>> import weakref
    >>> d = weakref.WeakValueDictionary()
    >>> x = foo()   
    >>> d['key'] = x
    >>> print d.items()
    [('key', <__main__.foo instance at 0x401eeb2c>)]
    >>> del x
    >>> print d.items()
    []
    >>> 

  Jp






More information about the Python-list mailing list