Assume I have the following Python script (os is used as a simple example here):
import os
def func():
# do something with os
print(os.getcwd())
import os
#func2()
# do something with os again
print(os.getcwd())
def func2():
import os
if __name__ == "__main__":
func()
Now my question is this:
Why does this script break when executing it telling me there is an UnboundLocalError: local variable 'os' referenced before assignment
? As os
is imported in the beginning of the script, I'd expect to be able to reference it for the rest of the script. What confuses me even more is that if I comment out the import in func
and instead call func2
, the script works just fine. Also, when I don't put the statements of func
into this function but instead just put them in the main guard, ir works fine as well.
Could someone please explain to me, what is going on here? I'd be thankful for any explanations!
So far I tried different orders of the imports and putting the import into functions and calling these functions. I think I noticed some patterns, but I don't understand what is going on under the hood.