PEP 8 says:
- Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function.
Any opinions?
EDIT (the reason I feel importing in functions can be a good idea):
Main reason: It can make the code clearer.
- When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using
from m import xxx
. Seeingm.xxx
in the function probably tells me more. Depending on whatm
is: Is it a well-known top-level module/package (import m
)? Or is it a sub-module/package (from a.b.c import m
)? - In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.