-1
>>> def fn(sc):
...     exec(sc)

This function runs perfectly fine.

1
  • The answer is still the same: either add global statements, explicitly reference globals()['A4'] = A4 + 1, or tell exec() what local namespace to update. Commented Aug 24, 2018 at 21:59

1 Answer 1

1

I think that executing "A4 = A4+1" inside fn without indicating that A4 is a global doesn't affect the global variable, since each function has its own local dictionary of variables.

If you need your fn to be a separate function containing an exec call, you can specify that your variable is a global, using the global keyword.

>>> def fn(sc):
...   exec(sc)
...
>>> value = 1
>>> fn('value += 1')
>>> value
1
>>> fn('global value; value += 1')
>>> value
2

Alternatively, exec will accept explicit globals and locals dictionaries passed into it. The help info for these functions notes that you can't reliably alter the value of a variable by updating locals(), but you can with globals(). As long as globals are what you want to update, you don't need to pass locals().

>>> def fn(sc):
...   exec(sc, globals())
...
>>> value = 1
>>> fn('value += 1')
>>> value
2
Sign up to request clarification or add additional context in comments.

5 Comments

Presumably the OP simplified it down to only call exec(). And clearly fn is not just an alias, since the namespace targets are different.
@khelwood what is the impact, if I pass fn("...", globals(), globals()) It seems to work
@TooGeeky If you're not inside a function, then there are no local variables, so locals() and globals() return the same thing. As long as you only want to alter global variables, passing globals() as both dictionaries should work.
@khelwood Perfect :) Thanks ... At last, there are some people genuinely to help on stackoverflow ... instead of just pressing down down(-1) button and marking it duplication. Appreciate the effort.
You're welcome. It was interesting to try out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.