Circular references (was: Defining VCL-like framework for Py

Alexander Staubo nospam-alex at mop.no
Fri May 21 13:05:26 EDT 1999


In article <1284891865-6060292 at hypernet.com>, gmcm at hypernet.com says...
[snip]
> Despite these drawbacks, I generally prefer ref counting to garbage
> collection. GC is generally nondeterminant - you know it _will_
> happen, but you have no idea _when_. So if your objects have some
> kind of outside resource open, you need to have a special free()
> method anyway instead of relying on freeing it in the destructor. 
> 
> I realize many people feel strongly the other way, and I'm not going 
> to fight about it. Neither solution is perfect. I'm just stating my 
> preference.

The solution is not to give up ref counting, but to augment it by 
permitting weak references to objects where necessary. For example, the 
collection example: It might be nice if you could write a collection type 
of object which did not "own" its references. Same thing with 
parent/child relationships.

Weak references can be implemented in several ways -- proxy objects and 
notifications, for instance.

For example,

class Parent:
  def setchild(self, child):
    self.child = make_proxy(self, child, self.proxydeletion)
  def proxydeletion(self, obj):
    if obj == self.child:
      self.child = None

I don't know Python's internals well, but basically a proxy object would 
(1) have to pass through all calls to its actual object, (2) it must not 
have a direct reference to its actual object, and (3) its __del__ method 
would call the deletion method.

As far as I can see, such a mechanism must be implemented in the Python 
core, since a proxy must be able to know when its object dies.

-- 
Alexander Staubo             http://www.mop.no/~alex/
"Give me an underground laboratory, half a dozen atom smashers and a beautiful 
girl in a diaphanous veil waiting to be turned into a chimpanzee, and I care 
not who writes the nation's laws." --S. J. Perelman




More information about the Python-list mailing list