def fun():
if False:
x=3
print(locals())
print(x)
fun()
output and error message:
{}
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-57-d9deb3063ae1> in <module>()
4 print(locals())
5 print(x)
----> 6 fun()
<ipython-input-57-d9deb3063ae1> in fun()
3 x=3
4 print(locals())
----> 5 print(x)
6 fun()
UnboundLocalError: local variable 'x' referenced before assignment
I am wondering how the python interpreter works. Note that x=3 doesn't run at all, and it shouldn't be treated as a local variable, which means the error would be " name 'x' is not defined". But look into the code and the error message, it isn't the case. Could anybody explain the mechanism principle of the compilation of the python interpreter behind this situation?