Import Module in Python
Import Module in Python
Import module is a syntax in python to import specific modules or header files like include in c or c++. In this article we have discussed about import module in python and the different syntaxes and how these work.
Import Module in Python | PrepInsta
What is Import in python?
Everyone writes codes. But how will a computer understand that a print means to print something in the output terminal. How will a machine understand what is sort whenever we write sort something. How will a python interpreter understand that if there is an end parameter inside the print function, it has to reconsider what will terminate a standard output instead of a newline unlike a default execution. So every computer language comes with some header files created by developers so that a student or a further developing person doesn’t need to rewrite codes again. These trivial codes are kept in other files, mostly called header files or modules. In python, the process to use a header file inside a piece of code is called import.
Below, all the code is using the module collections and using the defaultdict in collections. And it is giving an output: 2.
Syntax – 1
import module_name
In this syntax, you import a module. it searches the module in the local scope calling the function __import__(). In here to use the member variables and member functions or containers, you need to write the module_name.variable_or_funvtion_or_container_name in your code.
import collections
D = collections.defaultdict(int)
D[1]=2
print(D[1])
Syntax – 2
from module_name import class_name
In this syntax, you import a class or a variable or a constant or a container of a given module is imported. Then you can use the imported ones without any kind of module name.
from collections import defaultdict
D = defaultdict(int)
D[1]=2
print(D[1])
Syntax – 2.A
from module_name import *
In this syntax, you import all the classes and variables and constants containers of a given module are imported. Then you can use the imported ones without any kind of module name.
from collections import *
D = defaultdict(int)
D[1]=2
print(D[1])
Syntax – 3
import module_name as m_n
In this syntax, you import a module and rename it as anything.
import collections as cs
D = cs.defaultdict(int)
D[1]=2
print(D[1])
Syntax – 4
from module_name import class as cl
In this syntax, you import a class or a container or any member of a module and rename it as anything.
from collections import defaultdict as DD
D = DD(int)
D[1]=2
print(D[1])
Login/Signup to comment