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

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


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).


There was a detailed discussion of this topic on the Python mailing list in 2001:

https://mail.python.org/pipermail/python-list/2001-July/071567.html

Here are some of the reasons discussed in that thread. From Peter Hansen, here are three reasons not to have imports all at the top of the file:

Possible reasons to import in a function:

  1. Readability: if the import is needed in only one function and that's very unlikely ever to change, it might be clearer and cleaner to put it there only.

  2. Startup time: if you don't have the import outside of the function definitions, it will not execute when your module is first imported by another, but only when one of the functions is called. This delays the overhead of the import (or avoids it if the functions might never be called).

  3. There is always one more reason than the ones we've thought of until now.

Just van Rossum chimed in with a fourth:

  1. Overhead: if the module imports a lot of modules, and there's a good chance only a few will actually be used. This is similar to the "Startup time" reason, but goes a little further. If a script using your module only uses a small subset of the functionality it can save quite some time, especially if the imports that can be avoided also import a lot of modules.

A fifth was offered as local imports are a way to avoid the problem of circular imports.

Feel free to read through that thread for the full discussion.


Everyone else has already mentioned the PEPs, but also take care to not have import statements in the middle of critical code. At least under Python 2.6, there are several more bytecode instructions required when a function has an import statement.

>>> def f():
    from time import time
    print time()

>>> dis.dis(f)
  2           0 LOAD_CONST               1 (-1)
              3 LOAD_CONST               2 (('time',))
              6 IMPORT_NAME              0 (time)
              9 IMPORT_FROM              0 (time)
             12 STORE_FAST               0 (time)
             15 POP_TOP             

  3          16 LOAD_FAST                0 (time)
             19 CALL_FUNCTION            0
             22 PRINT_ITEM          
             23 PRINT_NEWLINE       
             24 LOAD_CONST               0 (None)
             27 RETURN_VALUE

>>> def g():
    print time()

>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (time)
              3 CALL_FUNCTION            0
              6 PRINT_ITEM          
              7 PRINT_NEWLINE       
              8 LOAD_CONST               0 (None)
             11 RETURN_VALUE