eval not reading variable inside a internal function

依然范特西╮ 提交于 2019-12-11 19:37:08

问题


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()

The above codes wouldn't work, giving error message: File "", line 1, in NameError: name 'aaa' is not defined

But if unmark the print(aaa) so both print lines exists, then both of them will work.

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...


回答1:


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.

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.

You probably don't want to be using eval anyway, there are extremely few cases where it is a good idea to use it.



来源:https://stackoverflow.com/questions/56492114/eval-not-reading-variable-inside-a-internal-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!