I find some strange behavior in my program after modifying the dictionary of local variables, and it makes me confused. If we execute the code below, we will get the result as the image I attached. And now I know I shouldn't modify the local variables using locals().
i=0
locals()[f'num_{i}'] = i
print(num_0)
def lc():
i=1
locals()[f'num_{i}'] = i
import pdb; pdb.set_trace()
print(num_1)
if __name__ == '__main__':
lc()
My questions are:
Why 'num_0' can be printed successfully while 'num_1' cant? (solved)
Why 'num_1' can be printed in pdb but 'print(num_1)' cant be executed? (solved)
Result:
python test.py
-----
0
-> print(num_1)
(pdb) p num_1
1
(pdb) c
Traceback (most recent call last):
File "test.py", line 13, in <module>
lc()
File "test.py", line 9, in lc
print(num_1)
NameError: name 'num_1' is not defined
Actually, I have a few ideas but I am not sure. I checked the dictionary of global variables, and 'num_0' is in it. So I suppose the first question is because the interpreter doesn't know that 'num_1' is in the dictionary of local variables, while 'num_0' is not only in the local dictionary but also in the global dictionary. As to the second question, I suppose pdb will know the modified local dictionary, so it can print 'num_1' successfully.
I hope someone can help to explain the two questions or give me some reference materials.