Reputation: 3642
I noticed many times that the import mod statement can be placed tightly before a call mod.something(). Though I noticed that usually developers put the import statement at the beginning of the source file. Is there a good reason for this?
I often use only a few functions from some module in particular place. It seems prettier to me to place the import statement tightly before the function call.
e.g.
# middle of the source file
import mod
mod.something()
What would you recommend and why?
Upvotes: 5
Views: 169
Reputation: 26174
One thing which can justify importing a module just before calling a function/using a class from that module is performance: sometimes initialization of a module can be expensive, because, for example, it involves loading and initializing a native library. If the code from a module is not always called, it can be a good idea to defer importing of that module until the last moment.
Upvotes: 6
Reputation: 47978
May as well move my comment here as an answer, though it feels a little redundant.
The PEP Style Guide calls for all imports to take place at the beginning of the module. This makes it easier for people to know what dependencies your module has, rather than having to dig through the entire source document.
As a caveat - on the rare occasion that an import would cause an error (circular imports are the best example of this) you can import immediately before you use some functionality. Generally speaking, however, this is bad form. If you are required to import somewhere other than the top of your module it usually indicates a design flaw.
Upvotes: 5