无法通过 exec() 语句更改函数中的全局变量?
为什么我不能使用 exec() 从函数内部更改全局变量?当赋值语句位于 exec() 之外时,它可以正常工作。这是我的问题的一个例子:
>>> myvar = 'test' >>> def myfunc(): ... global myvar ... exec('myvar = "changed!"') ... print(myvar) ... >>> myfunc() test >>> print(myvar) test
Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:
>>> myvar = 'test' >>> def myfunc(): ... global myvar ... exec('myvar = "changed!"') ... print(myvar) ... >>> myfunc() test >>> print(myvar) test
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据文档,
exec
语句采用两个可选表达式,默认为globals()
和locals()
,并且始终在locals()
中执行更改(如果有)一。所以,只要更明确/具体/精确......:
......你就能够将全局变量打乱到你的心里。
Per the docs, the
exec
statement takes two optional expressions, defaulting toglobals()
andlocals()
, and always performs changes (if any) in thelocals()
one.So, just be more explicit/specific/precise...:
...and you'll be able to clobber global variables to your heart's contents.
添加到亚历克斯的答案:虽然当你省略本地/全局参数时,它们默认为调用者的本地和全局参数,但这只是一个方便的黑客;它确实不意味着它们正在继承调用者的完整执行上下文。特别是
:嵌套作用域单元不可用于执行的代码。所以这失败了:
b。
global
声明不会延续到执行的代码中。因此,默认情况下,如您的示例所示,写入的变量将放入本地字典中。 使其发挥作用但是,您可以通过说“如果您能帮助的话,您实际上不想这样做”来 。
global
已经不太好了,exec
本身就是一种代码味道!除非确实别无选择,否则您不会想将它们结合起来。To add to Alex's answer: although when you omit the locals/globals arguments they default to the locals and globals of the caller, this only a convenience hack; it does not mean they are inheriting the full execution context of the caller. In particular:
a. nested scope cells are not available to the execed code. So this fails:
b.
global
declarations do not carry over into the execed code. So by default as in your example, written variables are put in the locals dictionary. However, you could make it work by sayingYou don't really want to be doing this if you can help it.
global
already isn't nice andexec
is pretty much a code smell in itself! You wouldn't want to combine them unless there was really no alternative.怎么样:
它在 Python 2.6 中对我有用。
编辑:实际上 Alex Martelli 的解释比我的好得多:)
How about this:
It worked for me in Python 2.6.
EDIT: Actually Alex Martelli's explanation is much better than mine :)
根据
exec
文档,以及代码字符串有两个可选参数:全局变量和局部变量。文档解释道:要改变全局变量,只需传递一个参数:
这是如何影响 exec 代码字符串中定义的函数的示例:
Per the
exec
docs, along with the code string it takes two optional parameters for globals and locals. The docs explains:To mutate globals, pass just one parameter:
An example of how this affects functions defined inside the exec code string: