This is an embarrassingly simple code, but producing very weird result:
import os
print(dir(os))
def main():
print(dir(os))
import os
if __name__ == '__main__':
main()
Note that there are 2 print(dir(os)) on lines 3 and 6. Very weirdly:
- Line 3 runs just fine and line 6 throws
UnboundLocalError: local variable 'os' referenced before assignment. - If I remove/comment out line 7 (
import osagain), the code runs just fine.
My Question:
- Why does the original code throw
UnboundLocalError? - Why does changing line 7 affect line 6? My understanding is that the Python interpreter runs sequentially and code never affect what comes before it.
Additional information:
- Replacing
oswith other modules gets the same result (e.g.numpy). - Reproduced with Python 3.6 - 3.9.
- My best guess is since
mainis a function, the interpreter will scan the function first and record all symbols. In this case, in the initial scan, it marks a local variableosin the function, and in the second run, the local variableosis referenced before assignment, and hence the error. Because replacing line 7 withimport os.pathalso gives the same error, but replace with "import os.path as osp` works fine again.