1

I have a problem with setting local variables with exec. I know of the drawback of using exec from a security perspective, but this code runs in a controlled environment.

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())

Output:

>>> f('A=3')
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3', 'A': 3}

Local variable A seems to have been set.


I change f to print A it fails:

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())
    print("A=", A)

Output:

>>> f('A=3')
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3', 'A': 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
NameError: name 'A' is not defined

However this works:

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())
    print("A=", eval('A'))

Output:

>>> f("A=3")
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3', 'A': 3}
A= 3

I also noticed this strange behaviour.

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())
    A=locals()['A']
    print("A=", A)

Output:

>>> f('A=3')
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
KeyError: 'A'

Now A is no longer in the locals dictionary. Does anyone have an explanation to this?

I am using Python 3.5

P.G.
  • 623
  • 6
  • 13

0 Answers0