[Python-Dev] Weakref design questions

Brian Quinlan brian@sweetapp.com
Fri, 18 Oct 2002 18:00:28 -0700


Guido van Rossum wrote:
> The instances of a type need to have a pointer added if the 
> type is to support weak refs to its instances.  We've only 
> done this for the obvious candidates like user-defined class 
> instances and a few others.  You must weigh the cost of the 
> extra pointer vs. the utility of being able to use weak refs 
> for a particular type.

Fair enough. 

> I'm sorry, but I don't understand why you're using weak references
> here at all.  Is it really the proxy function that you're after? 

I don't understand the question. 

> If
> you're worried about the complex object 'o' being referenced after the
> C library has killed it (a ligitimate concern), while the Python
> wrapper can be kept alive using the scenario you show, the Python
> wrapper py_o should set its pointer to 'o' to NULL when o's lifetime
> ends (or a little before) and make sure that methods on the wrapper
> raise an exception when the reference is NULL.

That is definitely one possible way to do it. However, I am wrapping a
complete DOM, with dozens of objects containing, collectively, hundreds
of methods. 

Adding an explicit check to each method seemed like a lot more pain than
using proxies.

Avoiding explicit checks also offers a potential performance advantage
because sometimes the objects are owned and no checking is required. In
that case I simply return the object directly without using a proxy.

> This is how all well-behaved wrapper objects behave; e.g. file and
> socket objects in Python check if the file is closed in each method
> implementation.

They contain far fewer methods. Also, there is more centralization is
file and socket objects i.e. they know themselves if they are in a valid
state or not, this is not true of my DOM objects.

Cheers,
Brian