When you call scope() Python sees that you have a local variable called os used inside your method (from import inside scope ), so this masks the global os . However, when you say print os , you did not reach the line and did local import, but you see an error regarding the link before the destination. Here are some other examples that might help:
>>> x = 3 >>> def printx(): ... print x
And back to your os example. Any os assignment has the same effect:
>>> os <module 'os' from 'C:\CDL_INSTALL\install\Python26\lib\os.pyc'> >>> def bad_os(): ... print os ... os = "assigning a string to local os" ... >>> bad_os() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in bad_os UnboundLocalError: local variable 'os' referenced before assignment
Finally, compare these 2 examples:
>>> def example1(): ... print never_used # will be interpreted as a global ... >>> def example2(): ... print used_later # will be interpreted as the local assigned later ... used_later = 42 ... >>> example1() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in example1 NameError: global name 'never_used' is not defined >>> example2() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in example2 UnboundLocalError: local variable 'used_later' referenced before assignment
source share