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
)?In the long run I think you'll appreciate having most of your imports at the top of the file, that way you can tell at a glance how complicated your module is by what it needs to import.
If I'm adding new code to an existing file I'll usually do the import where it's needed and then if the code stays I'll make things more permanent by moving the import line to the top of the file.
One other point, I prefer to get an ImportError
exception before any code is run -- as a sanity check, so that's another reason to import at the top.
I use pyChecker
to check for unused modules.