我正在尝试分析一些混乱的代码,该代码在函数内部使用全局变量非常频繁(我正在尝试重构代码,使函数仅使用局部变量)。有没有办法检测函数内的全局变量呢?
例如:
def f(x):
x = x + 1
z = x + y
return z
由于未在参数中给出,也未在函数内创建,因此全局变量在此处为y
。
我尝试使用字符串解析来检测函数内的全局变量,但这变得有些混乱了。我想知道是否有更好的方法来做到这一点?
编辑:如果有人感兴趣,这是我用来检测全局变量的代码(基于kindall的答案和Paolo对此问题的答案:在Python中捕获脚本的stdout):
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 装饰器:Capture stdout from a script in Python