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?
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.