Iterating over objects of a class
Scott David Daniels
Scott.Daniels at Acm.Org
Wed Dec 24 14:48:57 EST 2008
Kottiyath wrote:
> ...
> Having a registry inside the class instance and looping through them
> was the only clean thing I could think of.
> I understand that garbage collection would be an issue - but is there
> any way out?
Search for weakref in the documentatione.
In this case, I'd use a WeakValueDictionary() from id(obj) to obj.
Note id(obj) is guaranteed to be unique for all objects in existance,
but the id of a collected object may match the id of a new object.
>>> import weakref
>>> d = weakref.WeakValueDictionary()
>>> vs = [Int(n) for n in range(3, 500, 70)]
>>> for n in vs:
d[id(n)] = n
v = Int(n+1)
d[id(v)] = v
>>> for obj in d.values(): # values is safer than itervalues
print obj
>>> # note the above was the following, which fails:
>>> for v in d.values(): # values is safer than itervalues
print v
For extra credit, explain why values is better.
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list