Good or bad practice in Python: import in the middle of a file

flybywire picture flybywire · Jul 27, 2009 · Viewed 21k times · Source

Suppose I have a relatively long module, but need an external module or method only once.

Is it considered OK to import that method or module in the middle of the module?

Or should imports only be in the first part of the module.

Example:

import string, pythis, pythat
...
...
...
...
def func():
     blah
     blah 
     blah
     from pysomething import foo
     foo()
     etc
     etc 
     etc
...
...
...

Please justify your answer and add links to PEPs or relevant sources

Answer

Alex Martelli picture Alex Martelli · Jul 27, 2009

PEP 8 authoritatively states:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

PEP 8 should be the basis of any "in-house" style guide, since it summarizes what the core Python team has found to be the most effective style, overall (and with individual dissent of course, as on any other language, but consensus and the BDFL agree on PEP 8).