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

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.