Iterating through globals() dictionary

python iteration

821 观看


788 作者的声誉

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.

作者: sam-pyt 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


764793 作者的声誉


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])
作者: Martijn Pieters 发布者: 27.12.2017 05:22