# assigns 'os' to global namespace
import os
def main():
os.environ['blah'] = 'bloo' # <== which 'os'? python assumes local
# assigns 'os' to local namespace
import os.path
import
does two things. First, it creates a module object. Second it gives a name to that newly created module object. Giving something a name is assignment, hence the error message "UnboundLocalError: local variable 'os' referenced before assignment
".
Python has rules about the visibility of names and when they can be referenced. One of the rules is that there cannot be ambiguity in a function as to whether you mean to refer to a local name or a global name. If a local name is created anywhere inside a function that is the same as a global name, Python assumes that all references to that name inside the function refer to the local name (unless you specifically say otherwise).
Three possible fixes.
Drop the local import:
import os
def main():
os.environ['blah'] = 'bloo'
Drop the global import and move local import to the top of the function
def main():
import os.path
os.environ['blah'] = 'bloo'
Declare os
global at the beginning of your function so that the first reference uses the global:
import os
def main():
global os
os.environ['blah'] = 'bloo'
import os.path
A note about imports.
# has the same effect as 'import module'
# creates a reference named 'module'
import module.submodule
# imports submodule and creates a reference to it named 'submodule'
from module import submodule
# imports submodule and creates a reference to it named 'x'
import module.submodule as x