First of all, yes I know what I'm doing is bad. It's part of a hacky project that I'm trying for fun.
In Python 2.7, you could do this:
def myfunc():
exec('a=3')
print('Result: a = {}'.format(a))
myfunc()
And get Result: a = 3
Not so in Python 3.6, where you'll get NameError: name 'a' is not defined.
I can try to work around this by doing:
def myfunc():
exec('globals()["a"]=3')
print('Result: a = {}'.format(a))
myfunc()
Which in Python 3.6 gives the desired Result: a = 3 (and yes, has dangerous consequences by modifying globals). But of course it fails in the following case:
def myfunc():
a=2
exec('globals()["a"]=3')
print('Result: a = {}'.format(a))
myfunc()
Where I get Result: a = 2. Swapping in exec('a=3') here will also give Result: a = 2.
Question: Is there any hack in Python 3 that effectively allows me to assign to a variable in a function body?
exec('globals()["a"]=3')is just crazy. You should just doglobals()['a'] = 3. Anyway, just pass a custom namespace, e.g. somedictas locals then extract the variable using the dict. That will work.