From 82a58dc1b8645d40c6ed214742cc8ca69356c16d Mon Sep 17 00:00:00 2001 From: Mayur Garg Date: Sun, 3 Feb 2019 00:55:14 +0530 Subject: [PATCH] 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 --- guide/english/python/import-statements/index.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/guide/english/python/import-statements/index.md b/guide/english/python/import-statements/index.md index e2a6155f41..68376641c5 100644 --- a/guide/english/python/import-statements/index.md +++ b/guide/english/python/import-statements/index.md @@ -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. +