why globals() changed size during iteration?

Viewed 69

If use following code to print globals() key value pairs one by one:

for k, v in globals().items():
    # dict(globals()) working
    print(k, v)

will get such runtime error:

RuntimeError: dictionary changed size during iteration

I know dict(globals()) can freeze the dict, so no issue.

But I'm a little curious what actually changed during iteration? Is the exectuing function it self?

1 Answers

When you use global().items(), the items function creates a pair with iterators which are named k and v, that's the reason python says that dictionary changed size during iteration.

Here's an example proof:

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> for k, v in globals().items():
    pass

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    for k, v in globals().items():
RuntimeError: dictionary changed size during iteration
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'k': '__name__', 'v': '__main__'}
>>> 

Notice that after the error when I call globals() again it contains 2 more values.

Related