Added "Variations of Import statements" (#27356)

* Added "Variations of Import statements"

Added detailed list of simple variations of import statements which can be used in python.

* Fixed spelling
pull/34211/head^2
Mayur Garg 2019-02-03 00:55:14 +05:30 committed by Manish Giri
parent b56462c5ee
commit 82a58dc1b8
1 changed files with 16 additions and 0 deletions

View File

@ -114,4 +114,20 @@ from package import calculate_duration # Related third-party modules
from package.sibling import example # Local modules within the project
```
## Variations of Import statements
A good practice is to import only those modules or submodules that are being directly used in our program. Also we can rename the modules imported for a better use in our program. (Actual name of the module isn't changed, just by which name it is being referenced in our program is changed.)
1. **import my_module** - This imports the entire module as `my_module`. To use submodules, functions or classes of this module, we use the dot (associative) operator. For example - `a = my_module.my_sub_module.my_module_function()`
2. **import my_module.my_sub_module** - This allows us to only import the sub module `my_sub_module` from `my_module`. To use submodules, functions or classes of this module, we use the dot (associative) operator. For example - `a = my_module.my_sub_module.my_module_function()`
3. **from my_module import my_sub_module** - This allows us to only import the sub module `my_sub_module` from `my_module`. Rest sub modules aren't imported. To use functions or classes in this submodules or access its further sub module, we use the dot operator. Furthermore, this allows to access the sub module directly. This means that instead of `a = my_module.my_sub_module.my_module_function()`, we now use `a = my_sub_module.my_module_function()`
4. **import my_module as m** - This imports the entire module but now we can reference it as `m`. This means that instead of `a = my_module.my_sub_module.my_module_function()`, we now use `a = m.my_sub_module.my_module_function()`
5. **from my_module import my_sub_module as m** - This imports only the sub module which can be now referenced as `m`. This means that instead of `a = my_module.my_sub_module.my_module_function()`, we now use `a = m.my_module_function()`
One of the most important things to keep in mind when writing Python is legibility, and alphabetically sorting modules makes them faster to read and search through. Also, it is easier to verify that something is imported, and avoid duplicated imports.