【发布时间】:2015-10-16 00:39:04
【问题描述】:
我正在尝试分析一些杂乱无章的代码,这些代码恰好在函数中大量使用全局变量(我正在尝试重构代码,以便函数仅使用局部变量)。有没有办法检测函数中的全局变量?
例如:
def f(x):
x = x + 1
z = x + y
return z
这里的全局变量是y,因为它不是作为参数给出的,也不是在函数中创建的。
我尝试使用字符串解析来检测函数中的全局变量,但它变得有点混乱;我想知道是否有更好的方法来做到这一点?
编辑:如果有人感兴趣,这是我用来检测全局变量的代码(基于 kindall 的回答和 Paolo 对这个问题的回答: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
【问题讨论】:
-
碰巧我还写了一种捕获标准输出的方法。 :-) stackoverflow.com/a/16571630/416467
标签: python function global-variables