In Python it appears that import
s are truly lexically scoped. Is this true?
For example if you do this:
def some_function:
import sys
print sys.argv[0]
You will get an error:
Traceback (most recent call last):
File "example.py", line 4, in <module>
print sys.argv[0]
NameError: name 'sys' is not defined
In Perl,
use
statements are not lexically scoped, but Perl does not give you a syntax error if you attempt to define them lexically (i.e. within a subroutine). Doing this causes confusion and is considered very bad practice.
In Python this doesn't appear to be how things work. I believe I've read somewhere that it is considered good practice to always put your import
statements at the top of your code, but if they are truly lexically scoped as the example seems to show (meaning they can't be accessed outside of the scope in which they are defined), I don't see why it would be considered bad practice to just put them where you use them.
Is there any reason lexically scoping import
s would be bad practice in Python? If so, please explain why?
You will find a really good answer .... here Should Python import statements always be at the top of a module?
It's not so far.