Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place of the import statement

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?

like image 846
xralf Avatar asked Mar 12 '12 17:03

xralf


People also ask

Where do you put import statements?

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

What is an import statement?

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.

Why do we require the import statement?

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.

Where do you put Imports in Java?

In Java, the import statement is written directly after the package statement (if it exists) and before the class definition.


1 Answers

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.

like image 169
piokuc Avatar answered Sep 22 '22 10:09

piokuc