[Python-ideas] Alternative weakref implementation

MRAB python at mrabarnett.plus.com
Mon Dec 21 02:44:13 CET 2009

Greg Ewing wrote:
> 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?
What would be the cost of checking for every deallocation? If most
objects are never weakly referenced, then could the check be made
cheaper by setting a flag in an object if a weak reference is ever made
to it?

More information about the Python-ideas mailing list