eval not reading variable inside a internal functi

2019-08-27 22:18发布

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条回答
闹够了就滚
2楼-- · 2019-08-27 22:53

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.

查看更多
登录 后发表回答