不能通过`locals()`直接在python中设置局部变量

时间:2014-08-04 21:04:10

标签: python namespaces

我会保持这一短而简单。为什么会出现以下行为?

>>> globals()['x'] = 5
>>> x
5
>>> def f():
...    locals()['y'] = 7
...    y
...
>>> f()
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    f()
  File "<pyshell#31>", line 3, in f
    y
NameError: name 'y' is not defined

以下是可能使用的示例:

import opcode
def foo():
    locals().update(opcode.opmap)
    #do stuff

1 个答案:

答案 0 :(得分:2)

The documentation for locals() includes

  

注意:不应修改此词典的内容;更改可能不会影响解释器使用的本地和自由变量的值。