1

In Python it appears that imports 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 imports would be bad practice in Python? If so, please explain why?

tjwrona1992
  • 8,614
  • 8
  • 35
  • 98
  • I dislike lexically scoped imports because it's harder to find the modules that are being used that way. – Morgan Thrapp Sep 24 '15 at 20:44
  • 3
    https://www.python.org/dev/peps/pep-0008/#imports – jonrsharpe Sep 24 '15 at 20:44
  • Function based imports are common in case of issues related to circular imports, otherwise there's no good reason to import a module only at function level because even though the module is not accessible using the name `sys` it is still available through `sys.modules['sys']`. – Ashwini Chaudhary Sep 24 '15 at 20:48
  • Just about the most amusing case of "a reason to not put imports at the top" occurs in [q](https://github.com/zestyping/q/blob/6e8d2d6f91ea2765e210d9b7bb9bbfb39dd01d26/q.py#L67). And by amusing, I probably mean "terrible". – NightShadeQueen Sep 24 '15 at 20:57
  • "In Python it appears that imports are truly lexically scoped. Is this true?" Yes, `import` binds a name in *the local scope* to the desired module. – flow2k Dec 21 '19 at 09:27

1 Answers1

0

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.

Community
  • 1
  • 1
  • If you find a duplicate, please *flag as such* rather than providing a [link-only answer](http://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer) – jonrsharpe Sep 24 '15 at 20:52
  • What's "not so far"? – flow2k Dec 21 '19 at 09:21