pythonfunctionimportlocalunbound

Why UnboundLocalError occurs when importing inside function


For some reason this code produces error:

import os

def main():
    print(os.path.isfile('/bin/cat'))
    import os

if __name__ == '__main__':
    main()

Result:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    main()
  File "test.py", line 5, in main
    print(os.path.isfile('/bin/cat'))
UnboundLocalError: local variable 'os' referenced before assignment

Why it happens? Note that at beginning of both cases there is import os. Somehow additional import in the end of the body of a function affects whole scope of this function.

If you remove import inside the function, everything is fine (which is not surprising).

import os

def main():
    print(os.path.isfile('/bin/cat'))
    # import os

if __name__ == '__main__':
    main()

Result:

True

About possible duplicates: There are some similar questions, but regarding global variables, not imports.


Solution

  • If you import os in the global scope, you're creating a global variable called os. If you import os in local scope, you're creating a local variable called os. And if you try and use a local variable in a function before it's created, you get that error. Same as if you were explicitly assigning a variable.

    The same solutions apply, if you want the import inside the function to create a global variable, you can use the global keyword:

    def main():
        global os
        print(os.path.isfile('/bin/cat'))
        import os
    

    Or you could change your local import to use a different variable name so that your use of os is unambiguous.

    def main():
        print(os.path.isfile('/bin/cat'))
        import os as _os
    

    Though obviously this is just an example for demonstration, and there's no reason in this case to reimport os inside your function when you've already imported it globally.