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

This function runs perfectly fine.

TooGeeky
  • 133
  • 2
  • 10
  • The answer is still the same: either add `global` statements, explicitly reference `globals()['A4'] = A4 + 1`, or tell `exec()` what local namespace to update. – Martijn Pieters Aug 24 '18 at 21:59

1 Answers1

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
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Presumably the OP simplified it down to only call `exec()`. And clearly `fn` is not just an alias, since the namespace targets are different. – Martijn Pieters Aug 24 '18 at 21:53
  • @khelwood what is the impact, if I pass fn("...", globals(), globals()) It seems to work – TooGeeky Aug 24 '18 at 22:09
  • @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 Aug 24 '18 at 22:10
  • @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. – TooGeeky Aug 24 '18 at 22:13
  • 1
    You're welcome. It was interesting to try out. – khelwood Aug 24 '18 at 22:15