Python:为什么我不能使用locals()修改函数中的当前范围?

时间:2022-10-30 00:09:19

Why does creating/modifying a member of locals() not work within a function?

为什么创建/修改locals()的成员在函数内不起作用?

Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> # Here's an example of what I expect to be possible in a function:
>>> a = 1
>>> locals()["a"] = 2
>>> print a
2

>>> # ...and here's what actually happens:
>>> def foo():
...  b = 3
...  locals()["b"] = 4
...  print b
...
>>> foo()
3

2 个解决方案

#1


Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns.

为什么会这样?它旨在返回一个表示,并且从未打算用于编辑本地人。据文档警告,它无法保证作为此类工具。

#2


locals() return a copy of the namespace (which is the opposite of what globals() does). This means that any change you perform on the dictionary returned by locals() will have no effect. Check in dive into python at example 4.12.

locals()返回命名空间的副本(与globals()的副本相反)。这意味着您对locals()返回的字典执行的任何更改都将不起作用。在示例4.12中检查潜入python。

#1


Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns.

为什么会这样?它旨在返回一个表示,并且从未打算用于编辑本地人。据文档警告,它无法保证作为此类工具。

#2


locals() return a copy of the namespace (which is the opposite of what globals() does). This means that any change you perform on the dictionary returned by locals() will have no effect. Check in dive into python at example 4.12.

locals()返回命名空间的副本(与globals()的副本相反)。这意味着您对locals()返回的字典执行的任何更改都将不起作用。在示例4.12中检查潜入python。