- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我无法理解 Python 中“eval()”和“exec”的语义。 (此问题中的所有代码在 Python 2.7.8 和 Python 3.4.2 中的行为方式相同)。 documentation对于“评估”说:
If both [locals and globals] are omitted, the expression is executed in the environment where eval() is called.
“exec”有类似的语言。我显然不理解这句话,因为我希望下面程序定义的四个函数做同样的事情。
def h(x):
ls = locals()
exec('def i(y): return (w, x, y)', globals(), ls)
i = ls['i']
def j(y): return (w, x, y)
k = eval('lambda y: (w, x, y)')
l = lambda y: (w, x, y)
return i, j, k, l
w = 1
i, j, k, l = h(2)
他们没有。
>>> i(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in i
NameError: name 'x' is not defined
>>> j(3)
(1, 2, 3)
>>> k(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <lambda>
NameError: name 'x' is not defined
>>> l(3)
(1, 2, 3)
反汇编代码揭示了原因:“x”被“eval”和“exec”视为全局变量。
from dis import dis
print("This is `i`:")
dis(i)
print("This is `j`:")
dis(j)
print("This is `k`:")
dis(k)
print("This is `l`:")
dis(l)
print("For reference, this is `h`:")
dis(h)
输出:
This is `i`:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
This is `j`:
25 0 LOAD_GLOBAL 0 (w)
3 LOAD_DEREF 0 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
This is `k`:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
This is `l`:
27 0 LOAD_GLOBAL 0 (w)
3 LOAD_DEREF 0 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
For reference, this is `h`:
22 0 LOAD_NAME 0 (locals)
3 CALL_FUNCTION 0
6 STORE_FAST 1 (ls)
23 9 LOAD_CONST 1 ('def i(y): return (w, x, y)')
12 LOAD_NAME 1 (globals)
15 CALL_FUNCTION 0
18 LOAD_FAST 1 (ls)
21 EXEC_STMT
24 22 LOAD_FAST 1 (ls)
25 LOAD_CONST 2 ('i')
28 BINARY_SUBSCR
29 STORE_FAST 2 (i)
25 32 LOAD_CLOSURE 0 (x)
35 BUILD_TUPLE 1
38 LOAD_CONST 3 (<code object j at 0x7ffc3843c030, file "test.py", line 25>)
41 MAKE_CLOSURE 0
44 STORE_FAST 3 (j)
26 47 LOAD_NAME 2 (eval)
50 LOAD_CONST 4 ('lambda y: (w, x, y)')
53 CALL_FUNCTION 1
56 STORE_FAST 4 (k)
27 59 LOAD_CLOSURE 0 (x)
62 BUILD_TUPLE 1
65 LOAD_CONST 5 (<code object <lambda> at 0x7ffc3843c3b0, file "test.py", line 27>)
68 MAKE_CLOSURE 0
71 STORE_FAST 5 (l)
28 74 LOAD_FAST 2 (i)
77 LOAD_FAST 3 (j)
80 LOAD_FAST 4 (k)
83 LOAD_FAST 5 (l)
86 BUILD_TUPLE 4
89 RETURN_VALUE
上面的“j”和“l”具有我想要的行为。如何使用“eval”或“exec”获得此行为?
使用类而不是函数作为外部包装器确实改变了语义,但与期望的方式相反。它使“x”成为一个全局的。
class H:
x = 2
f = staticmethod(eval('lambda y: (w, x, y)'))
H.dis(H.f)
w = 1
H.f(3)
输出:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <lambda>
NameError: global name 'x' is not defined
包装在“类方法”中或将其保留为未绑定(bind)的实例方法只会让事情变得更糟。
使用字符串插值替换“x”适用于整数:
def h(x):
return eval('lambda y: (w, %r, y)' % x)
k = h(2)
dis(k)
w = 1
k(3)
输出:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_CONST 1 (2)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
(1, 2, 3)
但是,我不想假设“x”可以无损地转换为字符串并返回。该尝试在以下示例中被破坏:
k = h(lambda: "something")
k = h(open('some_file', 'w'))
cell = ["Wrong value"]
k = h(cell)
cell[0] = "Right value"
k(3)
由于 Python 正在寻找全局变量,一个明显的尝试是将“x”作为全局变量传递:
def h(x):
my_globals = {'w': w, 'x': x}
return eval('lambda y: (w, x, y)', my_globals)
k = h(2)
dis(k)
w = 1
k(3)
输出:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
(1, 2, 3)
这次尝试失败了,因为它过早地读取了“w”的值:
w = "Wrong value"
k = h(2)
w = "Right value"
k(3)
我最终确实找到了一种可行的方法,但我真的不喜欢它:
def h(x):
return eval('lambda x: lambda y: (w, x, y)')(x)
k = h(2)
dis(k)
w = 1
k(3)
输出:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_DEREF 0 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
(1, 2, 3)
特别是,如果我不知道传递给“eval”的字符串捕获的局部变量的完整列表,这将变得很痛苦。
你能做得更好吗?
更新 2014-12-25
寻找更多创建局部变量“x”的方法,我尝试了这个:
def h(x):
ls = locals()
exec('x = x\ndef i(y): return (w, x, y)', globals(), ls)
exec('_ = x\ndef j(y): return (w, x, y)', globals(), ls)
return ls['i'], ls['j'], ls['_'], ls['x']
i, j, check1, check2 = h(2)
assert check1 == 2
assert check2 == 2
w = 1
print("This is `i`:")
dis(i)
print("This is `j`:")
dis(j)
print("i(3) = %r" % (i(3),))
print("j(3) = %r" % (j(3),))
对“x”的额外赋值无效。断言验证“x”在本地字典中,但它没有被 lambda 捕获。这是输出:
This is `i`:
2 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
This is `j`:
2 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
对“i”和“j”的调用都崩溃了,提示没有全局变量“x”。
[编辑 2014-12-29:这仅在 Python 3 上成功。]
另一种创建局部变量的方法是这样的:
def h(x):
i = eval('[lambda y: (w, x, y) for x in [x]][0]')
j = eval('[lambda y: (w, x, y) for _ in [x]][0]')
return i, j
i, j = h(2)
w = 1
print("This is `i`:")
dis(i)
print("This is `j`:")
dis(j)
print("i(3) = %r" % (i(3),))
print("j(3) = %r" % (j(3),))
奇怪的是,在这种情况下,对“x”的额外赋值确实有影响。这确实有效,即“i”不同于“j”。这是输出:
This is `i`:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_DEREF 0 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
This is `j`:
1 0 LOAD_GLOBAL 0 (w)
3 LOAD_GLOBAL 1 (x)
6 LOAD_FAST 0 (y)
9 BUILD_TUPLE 3
12 RETURN_VALUE
i(3) = (1, 2, 3)
对“j”的调用崩溃,提示没有全局“x”,但“i”按预期工作并具有正确的字节码。
为什么这行得通,而上面的“失败 4”却行不通?决定本地“x”能否被捕获的规则是什么?这个设计的历史是什么? (这似乎很荒谬!)
最佳答案
我认为您希望您创建的函数继承创建它们的函数的局部环境,但也真正的全局环境(创建它们的函数)。这就是为什么您不喜欢他们将 x 称为全局变量,对吧?
下面围绕所需函数创建了一个“包装器”函数,所有函数都在同一个 exec 字符串中。当您调用或重新调用包装器时,创建函数的局部值将传入,从而创建一个新的包装闭包。
代码对在本地上下文中创建的新变量很敏感。确保函数和包装器名称都是已知的并且在其中具有值会遇到一些麻烦。
def wrap_f(code, gs, ls, wrapper_name, function_name):
ls[function_name] = ls[wrapper_name] = None
arglist = ",".join(ls.keys())
wrapcode = """
def {wrapper_name}({arglist}):
{code}
return {function_name}
""".format(wrapper_name=wrapper_name, arglist=arglist,
code=code, function_name=function_name)
exec(wrapcode, gs, ls)
wrapper = ls[wrapper_name]
return wrapper, wrapper(**ls)
所以,为了回答最初的问题,这段代码...
def h(x):
mcode = " def m(y): return (w, x, y)" # must be indented 4 spaces.
mwrap, m = wrap_f(mcode, globals(), locals(), "mwrap", "m")
return m
w = 1
m = h(2)
print m(3)
...产生这个输出:
(1, 2, 3)
这个例子展示了当 creator 函数中的局部变量发生变化时要做什么:
def foo(x):
barleycode = """
def barley(y):
print "barley's x =", x
print "barley's y =", y
"""
barleywrap, barley = wrap_f(barleycode, globals(), locals(),
"barleywrap", "barley")
barley("this string")
print
x = "modified x"
barley = barleywrap(**locals())
barley("new arg")
print
x = "re-modified x"
barley("doesn't see the re-mod.")
x = "the global x"
foo("outer arg")
这会产生输出:
barley's x = outer arg
barley's y = this string
barley's x = modified x
barley's y = new arg
barley's x = modified x
barley's y = doesn't see the re-mod.
关于python - Python 中 "eval"中捕获的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27638601/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!