This wants me to dig deeper in Python sources, but since there are many people on SO that already done that, I would love to hear their pointers.
>>> import os
>>> def scope():
... print os
... import os
...
>>> scope()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in scope
UnboundLocalError: local variable 'os' referenced before assignment
It seems to me that when parser interprets the file, it automatically creates local scope for scope function, that makes os “detached” from global scope.
Is it true? Anyone care to point me where I can find more about scope implementation?
EDIT: Also, this is not special case of imports, this works for usual variables too.
When you call
scope()Python sees that you have a local variable calledosused inside your method (from theimportinsidescope) so this masks the globalos. However when you sayprint osyou haven’t reached the line and executed the local import yet so you see the error regarding reference before assignment. Here are a couple of other examples that might help:And going back to your
osexample. Any assignment tooshas the same effect:Finally, compare these 2 examples: