# exec() an locals() puzzle

george trojan george.trojan at gmail.com
Wed Jul 20 12:56:02 EDT 2022

```I wish I could understand the following behaviour:

1. This works as I expect it to work:

def f():
i = 1
print(locals())
exec('y = i; print(y); print(locals())')
print(locals())
exec('y *= 2')
print('ok:', eval('y'))
f()

{'i': 1}
1
{'i': 1, 'y': 1}
{'i': 1, 'y': 1}
ok: 2

2. I can access the value of y with eval() too:

def f():
i = 1
print(locals())
exec('y = i; print(y); print(locals())')
print(locals())
u = eval('y')
print(u)
f()

{'i': 1}
1
{'i': 1, 'y': 1}
{'i': 1, 'y': 1}
1

3. When I change variable name u -> y, somehow locals() in the body of
the function loses an entry:

def f():
i = 1
print(locals())
exec('y = i; print(y); print(locals())')
print(locals())
y = eval('y')
print(y)
f()

{'i': 1}
1
{'i': 1, 'y': 1}
{'i': 1}

---------------------------------------------------------------------------NameError
Traceback (most recent call last)
Input In [1], in <cell line: 10>()      7     print(y)      8     # y
= eval('y')      9     #print('ok:', eval('y'))---> 10 f()

Input In [1], in f()      4 exec('y = i; print(y); print(locals())')
5 print(locals())----> 6 y = eval('y')      7 print(y)

File <string>:1, in <module>
NameError: name 'y' is not defined1.

Another thing: within the first exec(), the print order seems
reversed. What is going on?

BTW, I am using python 3.8.13.

George
```