0

In the following code, I am trying to use the statement 'a = b - c' to edit the local variable a:

def fun1(a, b, c):
  #a = b - c
  print(locals())
  exec('a = b - c', locals())
  return a

print(fun1(1, 10, 20))

output:

{'c': 20, 'b': 10, 'a': 1}
1

I am unable to modify the local variable a: it should return -10.

ardito.bryan
  • 429
  • 9
  • 22
  • 1
    Yes, you cannot dynamically modify local variables. Did you read the docs for [`locals`](https://docs.python.org/3/library/functions.html#locals)? Or for [`exec`](https://docs.python.org/3/library/functions.html#exec)? In particular: "Note The default locals act as described for function `locals()` below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function `exec()` returns." – juanpa.arrivillaga Jul 31 '20 at 03:37
  • 1
    As an aside, you *almost certainly* shouldn't be using `exec` to begin with. – juanpa.arrivillaga Jul 31 '20 at 03:38
  • What code/method should I be using to obtain the result I want? – ardito.bryan Jul 31 '20 at 03:43
  • Read the linked duplicate answers. – juanpa.arrivillaga Jul 31 '20 at 03:45

0 Answers0