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.