[Python-Dev] Weak Dictionary Iteration Behavior in Python 3

Georg Brandl g.brandl at gmx.net
Mon Sep 15 08:47:16 CEST 2008

Greg Ewing schrieb:
> Georg Brandl wrote:
>> In this case, what WeakKeyDictionary.keys() returns is not a view anyway,
>> so using list(self.data.keys()) in the method seems like a good compromise.
> I don't think that helps, because the implementation has
> to iterate over that to dereference the weak refs, and if
> that's done in Python code there's a chance for a weak
> ref to disappear in the process.

Yes, but in that case the ref will simply not be there anymore. It can't be
guaranteed anyway which objects will be alive at the precise moment you
call keys().  In contrast, iterating over the keys() view of the dictionary
one-by-one leads to an exception when one of the refs vanishes while still

See Armin's test case for an example that demonstrates this.


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-Dev mailing list