Get reference to "owner"

Jeremy Bowers newsfroups at jerf.org
Tue Mar 5 12:16:18 EST 2002


Robert Oschler wrote:

> Gerhard,
> 
> Excellent!!!  Never expected to find a language that could do this and it
> something I've wanted very badly for a long time.  Yes that's exactly what I
> meant.  B knows about the A that owns it without having to artificially pass
> a reference of A to B during construction.

If I'm reading that correctly, be sure you understand the limitation of 
that implementation: B is actually getting a reference to the thing 
that's creating it, which may or may NOT necessarily be it's parent. And 
that only if the thing that's creating it calls itself "self" (which is 
only convention, not requirement in Python). Attempting to create an 
instance of B() directly in a function fails with a keyerror, unless you 
have a "self" in that function.

You may consider it somewhat inconvenient, but in accordance with 
Python's "explicit rather then implicit" philosophy, you're probably 
better off passing an explicit reference to the parent. It's clear, it's 
flexible, it's standard, it doesn't have the laundry list of limitations 
and caveats the sample implementation does, and it also allows moving 
the parent pointer around, which is often useful. The only strike 
against it is a little extra typing; very little if there's a parent 
class you can move it into.

Also consider looking at the weakref module; trees with parent pointers 
are one of the defining reasons for the existance of that module.




More information about the Python-list mailing list