问题描述
使用内部函数时,它将读取在外部函数中定义的变量.但是使用eval()时,它以某种方式失败.它似乎与locals()的工作方式有关...但是我不确定如何以及为什么...
When using inner function, it reads variable defined in outer function. But somehow it fails when using eval(). It seems to be related to how locals() works... but I'm not sure how and why...
def main():
aaa = 'print this'
def somethingelse():
print(locals())
#print(aaa)
print(eval('aaa'))
print(locals())
somethingelse()
main()
以上代码无法正常工作,并显示错误消息: 文件",第1行,在 NameError:名称'aaa'未定义
The above codes wouldn't work, giving error message: File "", line 1, in NameError: name 'aaa' is not defined
但是,如果取消标记print(aaa)以便两个打印行都存在,则它们都将起作用.
But if unmark the print(aaa) so both print lines exists, then both of them will work.
我尝试在此print(aaa)命令之前和之后打印locals(),结果表明,如果标记了print(aaa)行,则两个locals()都为空{}.但是,如果未标记,则两个locals()都将是{aaa:'print this'}
I tried to print locals() before and after this print(aaa) command, it turns out that if the print(aaa) line is marked, both locals() would be empty {}. But if unmarked, then both locals() would be {aaa: 'print this'}
这让我感到困惑...
This is puzzling to me...
推荐答案
在编译Python代码时,编译器必须做一些特殊的事情才能允许从嵌套函数内部访问局部变量.这会使对变量的所有访问变慢,因此仅对它知道在内部函数中使用的变量进行访问.内部函数的名称空间中根本不存在外部函数的其他局部变量.
When your Python code is compiled, the compiler has to do special things to allow a local variable to be accessible from inside a nested function. This makes all access to the variable slower so it only does it for variables that it knows are used in the inner function. Other local variables from the outer function just don't exist in the inner function's namespace.
它无法分析用于eval
的字符串内部,因此它不知道代码正在尝试访问内部函数中不存在的变量.您需要直接从内部函数内部访问变量,以便编译器将其添加到该函数的局部变量中.
It can't analyse inside the string you use for eval
so it doesn't know that code is attempting to access a variable that otherwise wouldn't exist in the inner function. You need to access the variable directly from inside the inner function for the compiler to add it to the local variables for that function.
您可能仍然不想使用eval
,在极少数情况下,使用它是个好主意.
You probably don't want to be using eval
anyway, there are extremely few cases where it is a good idea to use it.
这篇关于评估不读取内部函数内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!