weird behaviour of late import and scopes

47 views Asked by At

I have just discovered this strange scoping behaviour of both Python 2 and 3. When I'm adding a late import for a sub-module, the main import of toplevel module stops working. Viable example:

import os


def start():
    import sys
    print('in modules?', 'os' in sys.modules)
    print('in globals?', 'os' in globals())
    print('in locals?', 'os' in locals())
    print('os =', os)

    import os.path
    os.path.exists('useless statement')


start()

The output will be:

in modules? True
in globals? True
in locals? False
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    start()
  File "test.py", line 9, in start
    print('os =', os)
UnboundLocalError: local variable 'os' referenced before assignment

Any ideas?

1

There are 1 answers

0
ronakg On BEST ANSWER

This is nothing special about import statements. It's just how the scoping works in Python. If you're assigning a value to a label, it is local to the scope unless explicitly defined global.

Try this code -

a = 2

def start():
    print a

    a = 3

start()

This also fails with UnboundLocalError as your code because statement a = 3 makes the label a local to function start.