dictionary size changed during iteration

Laszlo Nagy gandalf at shopzeus.com
Wed Apr 20 08:52:59 EDT 2011


Given this iterator:
class SomeIterableObject(object):
 ....
 ....
 def __iter__(self):
 ukeys = self.updates.keys()
 for key in ukeys:
 if self.updates.has_key(key):
 yield self.updates[key]
 for rec in self.inserts:
 yield rec
 ....
 ....
How can I get this exception:
RuntimeError: dictionary changed size during iteration
It is true that self.updates is being changed during the iteration. But 
I have created the "ukeys" variable solely to prevent this kind of 
error. Here is a proof of correctness:
>>> d = {1:1,2:2}
>>> k = d.keys()
>>> del d[1]
>>> k
[1, 2]
>>> k is d.keys()
False
So what is wrong with this iterator? Why am I getting this error message?
Thanks,
 Laszlo


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /