无法访问通过更改函数内部的 locals() 创建的变量
Can't access variable created by altering locals() inside function
在调用以变量名作为参数的函数时,我需要分配一些变量。
因此,我循环遍历具有所需名称的元组,通过 locals()
字典分配它们。
它有效,但我无法通过名称访问它们 - 即使在函数本身内部也是如此。
def function():
var_names = ("foo","bar","foobar")
for var_name in var_names:
locals()[var_name] = len(var_name)
print foo
投掷:
Traceback (most recent call last):
File "error_test.py", line 8, in <module>
function()
File "error_test.py", line 5, in function
print foo
NameError: global name 'foo' is not defined
使用以下代码效果很好:
def function():
var_names = ("foo","bar","foobar")
for var_name in var_names:
locals()[var_name] = len(var_name)
print locals()["foo"]
难道 locals()
dict 中只包含普通的函数变量吗?为什么它不起作用?
当你写:
for var_name in var_names:
locals()[var_name] = len(var_name)
你修改locals()
字典:
作为@user2357112 aptly linked in the docs:
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
因此修改 locals()
会删除局部变量,因此会出现 NameError: global name 'foo' is not defined
错误。
引用this post,解释似乎是在函数内部你只检索命名空间的副本而不是命名空间本身:
locals does not actually return the local namespace, it returns a copy. So changing it does nothing to the value of the variables in the local namespace.
我仍在寻找一种方法来更改函数内的命名空间,所以我很乐意看到有人用比这更好的解决方案来回答这个问题。
在调用以变量名作为参数的函数时,我需要分配一些变量。
因此,我循环遍历具有所需名称的元组,通过 locals()
字典分配它们。
它有效,但我无法通过名称访问它们 - 即使在函数本身内部也是如此。
def function():
var_names = ("foo","bar","foobar")
for var_name in var_names:
locals()[var_name] = len(var_name)
print foo
投掷:
Traceback (most recent call last):
File "error_test.py", line 8, in <module>
function()
File "error_test.py", line 5, in function
print foo
NameError: global name 'foo' is not defined
使用以下代码效果很好:
def function():
var_names = ("foo","bar","foobar")
for var_name in var_names:
locals()[var_name] = len(var_name)
print locals()["foo"]
难道 locals()
dict 中只包含普通的函数变量吗?为什么它不起作用?
当你写:
for var_name in var_names:
locals()[var_name] = len(var_name)
你修改locals()
字典:
作为@user2357112 aptly linked in the docs:
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
因此修改 locals()
会删除局部变量,因此会出现 NameError: global name 'foo' is not defined
错误。
引用this post,解释似乎是在函数内部你只检索命名空间的副本而不是命名空间本身:
locals does not actually return the local namespace, it returns a copy. So changing it does nothing to the value of the variables in the local namespace.
我仍在寻找一种方法来更改函数内的命名空间,所以我很乐意看到有人用比这更好的解决方案来回答这个问题。