Reputation: 42349
This is a question regarding good python
coding and positioning.
I have a somewhat large code for which I use lots of external modules/packages/functions. Currently I load all of them at the very top of the code because that's how I've seen it done. This is bothersome for example when I need to comment out a block of the code for testing because then I need to go up, look for the modules that block was using and comment them out too. I know I don't have to do this last part, but I do it for consistency since I don't like to import things I won't be using.
If the imported modules where listed right above the block that makes use of them, this process would be easier and the code would be easier to follow, at least for me.
My question is whether it is recommended to import all modules at the beginning of the code or should I do it throughout the code as necessary?
Upvotes: 2
Views: 1533
Reputation: 1350
Its officially recommended to import at the beginning, see PEP8:
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Imports should be grouped in the following order:
- standard library imports
- related third party imports
- local application/library specific imports
- You should put a blank line between each group of imports.
Put any relevant
__all__
specification after the imports.
Upvotes: 7
Reputation: 12401
Well, I would say do it however is easiest for you. But I think following the PEP8 recommendation (already referenced in another answer) is generally the best method. It's easier to see everything your module references this way all in one place, and that's where new programmers will look to add their imports to your code later.
As an aside, this page gives one reason why you might violate this convention, https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead:
Note that putting an import in a function can speed up the initial loading of the module, especially if the imported module might not be required. This is generally a case of a "lazy" optimization -- avoiding work (importing a module, which can be very expensive) until you are sure it is required.
If the import of a module is expensive (it's huge, or has side effects), then you might want to put it later. In short, if you want to follow this part of 'The Zen of Python':
Although practicality beats purity.
wrt to your import placement, then do so.
Upvotes: 1