简体   繁体   中英

Iterating through globals() dictionary

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM