[Python-ideas] Alternative weakref implementation

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Dec 21 01:13:35 CET 2009


I've been thinking about an alternative implementation
of weak references that would remove the limitation of
only certain types being weakly referenceable.

This limitation can be a nuisance sometimes. The
justification for it appears to be that you can't
build a cycle exclusively out of objects that don't
contain any mutable references, so there is no need
to create weakrefs to such objects.

However, avoiding cycles is not the only reason for
using weakrefs. They can also be useful for setting
up callbacks to be triggered when an object is
deallocated.

The restriction would be unnecessary if weakrefs could
be implemented without incurring any overhead in the
object being weakly referenced. This could be done
by keeping a global dictionary, with keys that are
uncounted references to weakly referenced objects, and
values that are lists of weakref objects.

Whenever an object is deallocated, the dict would be
checked to see if there are any weak references to it,
and if so they would be made dead and their callbacks
called, and then the dict entry would be removed.

Can anyone see any serious flaws in this scheme?

-- 
Greg



More information about the Python-ideas mailing list