Counting number of objects

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jan 27 11:40:27 EST 2009


Kottiyath wrote:
> So, in a higher level class, have a weakref list which contains a
> reference to each person. Total count will be len(list) at any time.
> 
> Now, I couldnt find a weakref list - so I am using WeakKeyDictionary
> with the value as None - since len(dict) also should give me the data
I typically use a WeakValueDictionary, with the key id(obj).
...
> Now, the only two operations that I am doing are ->
> __init__:
>   d = weakref.WeakKeyDictionary()
> 
> method y:
>   x = aa()
>   d[x] = None
> 
> method z:
>   total = len(d)

At least at one point, the WeakValueDictionary was more stable.  I don't
remember the details, but I remember my work-around.  If you do have
troubles, try using almost the same code you now use, but substitute for
the obvious lines above:
     d = weakref.WeakValueDictionary()
and
     d[id(x)] = x


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list