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?
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
An import statement tells the compiler the path of a class or the entire package. It is unlike “#include” in C++, which includes the entire code in the program. Import statement tells the compiler that we want to use a class (or classes) that is defined under a package.
The import statement can be used to import an entire package or sometimes import certain classes and interfaces inside the package. The import statement is written before the class definition and after the package statement(if there is any). Also, the import statement is optional.
In Java, the import statement is written directly after the package statement (if it exists) and before the class definition.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With