Python NameError in a function body

200 Views Asked by At

I have two blocks of python code, one works, and the other doesn't.


Working block:

env = {'user':'xyz'}
for key, value in env.items():
    exec("{} = value".format(key))

print(user)

output:

xyz


The block, which doesn't work:

def test():
    env = {'user':'xyz'}
    for key, value in env.items():
        exec("{} = value".format(key))

    print(user)

test()

output:

NameError: name 'user' is not defined


The only difference I see is that the first block is being called in the global scope.

Could you please explain?

Many thanks!

PS: With all due respect, I know, I should avoid using exec() but what if I want to.

1

There are 1 best solutions below

1
On

I recommend you reading this

You have to use locals() or exec or eval to access variables defined by exec in a function in Python3.

def test():
    env = {'user': 'xyz'}
    for key, value in env.items():
        exec("{} = value".format(key))
    exec("print(user)")
    print(locals()['user'])
    print(eval("user"))
 
test()

It should be noted that, if you attempt to store value returned from eval. You will get NameError.

def test():
    env = {'user': 'xyz'}
    for key, value in env.items():
        exec("{} = value".format(key))
    user = eval("user")
    print(user)

test()

returns

Traceback (most recent call last):
  File "D:/Git/sscgc/test.py", line 8, in <module>
    test()
  File "D:/Git/sscgc/test.py", line 5, in test
    user = eval("user")
  File "<string>", line 1, in <module>
NameError: name 'user' is not defined