dictionary size changed during iteration

Mel mwilson at the-wire.com
Wed Apr 20 10:18:59 EDT 2011


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:
> 
>>>>  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?

`ukeys` isn't a different dictionary from `self.updates.keys`  I'ts merely 
another name referring to the same dict object.  I think

ukeys = dict (self.updates.keys)

would do what you want.

	Mel.




More information about the Python-list mailing list