我尝试在函数的局部范围内使用eval()。但是,它始终在全局范围内进行评估。
自包含的示例:
1-此代码有效:
var1 = 1 var2 = 2 var3 = 3 myDict = dict((name, eval(name)) for name in ["var1", "var2", "var3"]) print(myDict["var1"])
2-抛出NameError为lvar1
NameError
lvar1
def test1(): lvar1 = 1 lvar2 = 2 lvar3 = 3 myDict = dict((name, eval(name)) for name in ["lvar1", "lvar2", "lvar3"]) print(myDict["lvar1"])
3-与2相同的结果。
def test2(): lvar1 = 1 lvar2 = 2 lvar3 = 3 myDict = dict((name, eval(name), locals()) for name in ["lvar1", "lvar2", "lvar3"]) print(myDict["lvar1"])
保存locals()(或vars())调用的结果以返回函数的本地范围。否则,locals()在生成器表达式内部将返回gen-expr的本地范围。
locals()
vars()
def test3(): lvar1 = 1 lvar2 = 2 lvar3 = 3 scope = locals() myDict = dict((name, eval(name, scope)) for name in [ "lvar1", "lvar2", "lvar3"]) print(myDict["lvar1"])
顺便说一句,您不需要明确的理解即可构建该命令:
# copy() avoids quirky, unexpected updates if something else (like a debugger) # accesses locals() or f_locals myDict = locals().copy() # or vars().copy()