=================================================================================
============================================
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. The best practice of placing the import statements is to use your best judgements:
i) Place the statement at the top of the file. Good reasons to import modules at the head of the importing module only are:
i.a) The code within the module can be more easily moved around. If the import statements are scattered around your module you have to be careful not to move any code that depends upon an imported module above that module's import statement.
i.b) it's a trivial cost that's only paid once, namely, the module initialization only occurs once.
ii) Imports at the top enhance readability.
iii) Some modules, e.g. in Apache Spark's Python API,
have implicit dependencies that need to be imported or initialized first, and a top-level import could lead to violations of the required order of execution.
iv) Do not use the rule in i) if there is inconsistence.
v) Putting imports within a function will cause calls to that function to take longer. However, putting the import statement inside of a function can prevent circular dependencies. For instance, if there are two modules, x.py and y.py, and they both need to import each other, which causes a circular dependency when you import one of the modules causing an infinite loop. If the import statement is moved into one of the modules then it won't try to import the other module till the function is called, and that module will already be imported, so no infinite loop.
In such cases, imports in a function won't run until that function is called.
vi) Some common modules take a noticeable time to import.
vii) Saves some memory and startup time by not importing the module until needed.
viii) Imports under the __name__ == "__main__" guard seems very reasonable.
ix) Parallel processing might require that the imports are in the function.
Some examples are below:
i) If the --mail option is not supplied then the module fancy.mail.library.module is never referenced, and thus you can avoid importing it and avoid failing if the dependency is missing.
![If the --mail option is not supplied then the module fancy.mail.library.module is never referenced, and thus you can avoid importing it and avoid failing if the dependency is missing](images/4393a.png)
ii)
|