dictionary size changed during iteration

John Nagle nagle at animats.com
Fri Apr 22 08:22:50 CEST 2011


On 4/20/2011 5:52 AM, Laszlo Nagy wrote:
> 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:

    I think we need to see some more code here.

    Also, what version of Python are you running?

http://docs.python.org/library/stdtypes.html

says "keys()
     Return a copy of the dictionary’s list of keys."

So "ukeys" should be a unique list, not some part of
self.updates or a generator.

At least in Python 2.6, keys() does return a unique list.  Each
call to "keys()" returns a new list object unconnected to the
dictionary from which the keys were extracted.  But someone may
have decided in a later version to return a generator, as
an optimization.  Did that happen?

				John Nagle





More information about the Python-list mailing list