5

I am (attempting) to use globals() in my program to iterate through all the global variables. This is how I went about it:

for k, v in globals().iteritems():
    function(k, v)

Of course, in doing so, I just created 2 more global variables, k and v. So I get this exception:

RuntimeError: dictionary changed size during iteration

And, here are my various unsuccessful attempts at solving the issue:

# Attempt 1:

g = globals()
for k, v in globals().iteritems():
    function(k, v)

# Attempt 2 (this one seems to work, but on closer inspection it duplicates 
#the last item in the dictionary, because another reference is created to it):

k = v = None
for k, v in globals().iteritems():
    function(k, v)

I have seen posts like this that deal with the same exception. This is different because there is no way to assign a variable to each dictionary entry without making a variable name for it... and doing so raises an error.

1 Answer 1

11

You are using iteritems(), which iterates over the live dictionary. You can trivially avoid the problem by creating a copy of the items first; in Python 2 just use globals().items():

for k, v in globals().items():
    function(k, v)

In Python 3, you'd use list() to materialise all item pairs into a list first:

for k, v in list(globals().items()):
    function(k, v)

That list will never be so large as to be an issue; module globals are rarely larger than a few dozen items.

If you feel that even a few dozen tuples are an issue, then create a list for the keys only:

for k in list(globals()):  # python 2 and 3
    function(k, globals()[k])
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.