0

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.

  • 1
    Why do you import os inside func and func2? importing it globally should be sufficient. In general imports should be at the top of the module (file). the only reason I'd put one in a function, would be because it's a very large module or pricy in runtime, and the function that uses it isn't called regularly. other than that, no reason to put it inside functions – Meny Issakov Jan 19 '23 at 14:32
  • `import` is a kind of assignment statement. Your in-function `import `of `os` makes `os` a local variable, so `os.getcwd` refers to that, not the global variable `os`. – chepner Jan 19 '23 at 14:34
  • `import os` makes `os` a local variable inside the function, the same as assigning `os = ...` would. See the duplicate above. – deceze Jan 19 '23 at 14:34

0 Answers0