-1

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?

2
  • 1
    No. There isn't a good or easy way. But the good news is you don't need to. Commented Nov 12, 2019 at 21:29
  • exec('globals()["a"]=3') is just crazy. You should just do globals()['a'] = 3. Anyway, just pass a custom namespace, e.g. some dict as locals then extract the variable using the dict. That will work. Commented Nov 12, 2019 at 21:30

1 Answer 1

-1
def myfunc():
    exec('a=3', locals(), globals())
    print('Result: a = {}'.format(a))


myfunc()
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, ok that works in the first case, but in the second case (when I put a=2 first) the result is still Result: a = 2. It looks like this is just functionally equivalent to exec('globals()["a"]=3')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.