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.
from m import xxx
. Seeing m.xxx
in the function probably tells me more. Depending on what m
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
)?