exec 如何与当地人合作? [英] How does exec work with locals?

查看:28
本文介绍了exec 如何与当地人合作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为这会打印 3,但它会打印 1:

I thought this would print 3, but it prints 1:

def f():
    a = 1
    exec("a = 3")
    print(a)

推荐答案

这个问题在 Python3 错误列表中有一些讨论.最终,要获得此行为,您需要执行以下操作:

This issue is somewhat discussed in the Python3 bug list. Ultimately, to get this behavior, you need to do:

def foo():
    ldict = {}
    exec("a=3",globals(),ldict)
    a = ldict['a']
    print(a)

如果您查看 关于 exec 的 Python3 文档,您将看到以下注释:

And if you check the Python3 documentation on exec, you'll see the following note:

默认 locals 的行为如以下函数 locals() 所述:不应尝试修改默认 locals 字典.如果您需要在函数 exec() 返回后查看代码对 locals 的影响,请传递一个显式的 locals 字典.

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

这意味着单参数 exec 不能安全地执行任何会绑定局部变量的操作,包括变量赋值、导入、函数定义、类定义等.它可以赋值给全局变量,如果它使用 global 声明,但不使用本地声明.

That means that one-argument exec can't safely perform any operations that would bind local variables, including variable assignment, imports, function definitions, class definitions, etc. It can assign to globals if it uses a global declaration, but not locals.

参考错误报告中的特定信息,Georg Brandl 说:

Referring back to a specific message on the bug report, Georg Brandl says:

动态修改函数的局部变量不是可能没有几个后果:通常,函数局部变量不是存储在字典中,但数组,其索引确定在从已知语言环境编译时间.这至少与新的冲突由 exec 添加的本地人.旧的 exec 语句绕过了这一点,因为编译器知道如果没有全局/本地参数的 exec 发生在函数中,该命名空间将是未优化的",即不使用本地人数组.由于 exec() 现在是一个普通函数,编译器会不知道什么是exec"可能是必然的,因此不能治疗的是特别.

To modify the locals of a function on the fly is not possible without several consequences: normally, function locals are not stored in a dictionary, but an array, whose indices are determined at compile time from the known locales. This collides at least with new locals added by exec. The old exec statement circumvented this, because the compiler knew that if an exec without globals/locals args occurred in a function, that namespace would be "unoptimized", i.e. not using the locals array. Since exec() is now a normal function, the compiler does not know what "exec" may be bound to, and therefore can not treat is specially.

重点是我的.

所以它的要点是 Python3 可以通过默认允许这种行为来更好地优化局部变量的使用.

So the gist of it is that Python3 can better optimize the use of local variables by not allowing this behavior by default.

为了完整起见,正如上面评论中提到的,这 确实在 Python 2.X 中按预期工作:

And for the sake of completeness, as mentioned in the comments above, this does work as expected in Python 2.X:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     a = 1
...     exec "a=3"
...     print a
... 
>>> f()
3

这篇关于exec 如何与当地人合作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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