为什么 exec 中的闭包会被破坏?

发布于 2024-08-30 14:40:10 字数 563 浏览 2 评论 0原文

在 Python 2.6 中,

>>> exec "print (lambda: a)()" in dict(a=2), {}
2
>>> exec "print (lambda: a)()" in globals(), {'a': 2}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> exec "print (lambda: a).__closure__" in globals(), {'a': 2}
None

我希望它打印 2 两次,然后使用单个 cell 打印一个元组。 3.1中也是同样的情况。这是怎么回事?

In Python 2.6,

>>> exec "print (lambda: a)()" in dict(a=2), {}
2
>>> exec "print (lambda: a)()" in globals(), {'a': 2}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> exec "print (lambda: a).__closure__" in globals(), {'a': 2}
None

I expected it to print 2 twice, and then print a tuple with a single cell. It is the same situation in 3.1. What's going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多孤肩上扛 2024-09-06 14:40:10

当您将字符串传递给 execeval 时,它会在考虑全局变量或局部变量之前将该字符串编译为代码对象。因此,当您说:

eval('lambda: a', ...)

这意味着:

eval(compile('lambda: a', '<stdin>', 'eval'), ...)

compile 无法知道 a 是一个 freevar,因此它将其编译为全局引用:

>>> c= compile('lambda: a', '<stdin>', 'eval')
>>> c.co_consts[0]
<code object <lambda> at 0x7f36577330a8, file "<stdin>", line 1>
>>> dis.dis(c.co_consts[0])
  1           0 LOAD_GLOBAL              0 (a)
              3 RETURN_VALUE        

因此要使其工作,您必须将 a 放入全局变量中,而不是局部变量中。

是的,这有点狡猾。但我想这对你来说就是 exec 和 eval ......它们不应该是好的。

When you pass a string to exec or eval, it compiles that string to a code object before considering globals or locals. So when you say:

eval('lambda: a', ...)

it means:

eval(compile('lambda: a', '<stdin>', 'eval'), ...)

There's no way for compile to know that a is a freevar, so it compiles it to a global reference:

>>> c= compile('lambda: a', '<stdin>', 'eval')
>>> c.co_consts[0]
<code object <lambda> at 0x7f36577330a8, file "<stdin>", line 1>
>>> dis.dis(c.co_consts[0])
  1           0 LOAD_GLOBAL              0 (a)
              3 RETURN_VALUE        

Therefore to make it work you have to put a in the globals and not the locals.

Yeah, it's a bit dodgy. But then that's exec and eval for you I suppose... they're not supposed to be nice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文