我尝试在函数的局部范围内使用 eval().但是它总是在全局范围内进行评估.
I try to use eval() in a local scope of a function. However it always evaluate in the global scope.
自包含示例:
1- 此代码有效:
var1 = 1
var2 = 2
var3 = 3
myDict = dict((name, eval(name)) for name in ["var1",
"var2",
"var3"])
print(myDict["var1"])
2- 为 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 相同的结果.
3- Same outcome as 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 的局部作用域.
Save the result of locals()
(or vars()
) call to return the function's local scope. Otherwise, locals()
inside the generator expression will return the gen-expr's local scope.
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"])
顺便说一句,您不需要明确的理解来构建该字典:
BTW, you don't need an explicit comprehension to build that dict:
# copy() avoids quirky, unexpected updates if something else (like a debugger)
# accesses locals() or f_locals
myDict = locals().copy() # or vars().copy()
这篇关于Python:如何在函数的本地范围内运行 eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!
[英文标题]Python: How can I run eval() in the local scope of a function
声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。