Python:如何在函数的本地范围内运行 eval() [英] Python: How can I run eval() in the local scope of a function

查看:32
本文介绍了Python:如何在函数的本地范围内运行 eval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在函数的局部范围内使用 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆