RuntimeError: dictionary changed size during iteration

John Machin sjmachin at lexicon.net
Tue Dec 9 05:27:44 CET 2008


On Dec 9, 3:00 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote:
> > On Dec 8, 6:26 pm, Terry Reedy <tjre... at udel.edu> wrote:
> >> Robert Dailey wrote:
> >> > stuff = vars()
>
> >>  >>> vars() is globals()
> >> True
>
> >> > for key in stuff:
>
> >> You just changed globals, which is aliased as stuff. Stuff changes.
>
> >> >     print( key, '--', stuff[key] )
>
> >> > I get the following error message:
> >> > ('CopyEmotionFX', '--', <function CopyEmotionFX at 0x0205BF70>)
> >> > Traceback (most recent call last):
> >> >   File "C:\IT\work\jewett\depends.py", line 12, in <module>
> >> >     for key in stuff:
> >> > RuntimeError: dictionary changed size during iteration
>
> >> > Why is this happening?
>
> > How am I changing globals()? I'm simply iterating the keys in the dict.
> > Can someone explain what is going on please?
>
> You create an new name "key":
>
> for key in stuff
>
> I suppose you could do this:
>
> key = None
> stuff = vars()
> for key in stuff:

but both 'key' and 'stuff' will appear in the dict, possibly causing
confusion; another reason why

> even better would be:
>
> for key in vars().copy():
>
> because that protects you from cases where globals() change inside the
> for loop.



More information about the Python-list mailing list