While trying to create a list comprehension and then run it I have become perplexed by the mercuriality of Python (3.5)'s exec()
function.
I would expect all of the following examples to print out 10
, but only (a) does. I know that the function takes the keyword arguments globals, locals
but in all of these situations exec
seems to have full access to foo
. I have tried the code in the console as well as in a file but to no avail.
Why do (b), (c) and (d) not work as intended?
Is there a way of getting the altered variables after they have been exec'd within a function?
Does it involve the dreaded global variables?
(a)
def foo():
return 10
exec("a = foo()")
print(a) #Prints 10
(b)
def foo():
return 10
def func():
exec("b = foo()")
print(b) #NameError: name 'b' is not defined
func()
(c)
def foo():
return 10
def func(bar):
exec("c = bar()")
print(c) #NameError: name 'c' is not defined
func(foo)
(d)
def func():
def foo():
return 10
exec("d = foo()")
print(d) #NameError: name 'd' is not defined
func()