我想分析一些凌乱的代码,这恰好在函数中使用全局变量相当沉重(我试图重构代码,以便函数只使用局部变量)。有什么方法可以检测函数内的全局变量吗?检测python函数中的所有全局变量?
例如:
def f(x):
x = x + 1
z = x + y
return z
这里全局变量是y
,因为它不作为参数给出的,并且也不是该函数内创建的。
我试图使用字符串解析来检测函数内的全局变量,但它变得有点混乱;我想知道是否有更好的方法来做到这一点?
编辑:如果有人有兴趣,这是我使用来检测全局变量的代码(基于kindall的答案和保罗的回答这个问题:Capture stdout from a script in Python):
from dis import dis
def capture(f):
"""
Decorator to capture standard output
"""
def captured(*args, **kwargs):
import sys
from cStringIO import StringIO
# setup the environment
backup = sys.stdout
try:
sys.stdout = StringIO() # capture output
f(*args, **kwargs)
out = sys.stdout.getvalue() # release output
finally:
sys.stdout.close() # close the stream
sys.stdout = backup # restore original stdout
return out # captured output wrapped in a string
return captured
def return_globals(f):
"""
Prints all of the global variables in function f
"""
x = dis_(f)
for i in x.splitlines():
if "LOAD_GLOBAL" in i:
print i
dis_ = capture(dis)
dis_(f)
dis
默认情况下不返回输出,所以如果你想操作dis
作为一个字符串的输出,你必须使用Paolo写的捕获装饰器,并发布在这里:Capture stdout from a script in Python
碰巧我还写了一种捕获stdout的方法。 :-) http://stackoverflow.com/a/16571630/416467 – kindall