Can someone explain this weakref behavior?

David MacQuigg dmq at gain.com
Fri Jun 11 15:00:42 EDT 2004


On Fri, 11 Jun 2004 13:56:19 -0400, "Tim Peters" <tim.one at comcast.net>
wrote:

>That will pass under CPython today, but there's no general guarantee about
>exactly when a weak dict will notice that keys (or values) have become
>unreachable by strong references.

OUCH!!  We just built a module that uses weak references to keep a
"robust count" of instances in various classes.  The claim is that
this is more robust than simply incrementing and decrementing class
variables using __init__ and __del__.   The module seems to be working
OK, immediately deleting the weak reference as soon as all references
to the corresponding instance are deleted.

If I understand you correctly, there is some chance that a future
implementation of Python may have the weak references "out-of-sync"
with the actual count of live instances.  Is that a remote
possibility, or something quite likely to occur?  I have to decide now
whether to rip out some risky code.

Is there a good way to track the count of instances?  If not, would it
make sense to request a guarantee on the current behavior of weak
references?  Maybe it could be an option, assuming there is some
performance penalty, an option to be used when accuracy is more
important than speed.

-- Dave




More information about the Python-list mailing list