Import Module in Python

Import in python is similar to #include header_file in C/C++.In Python, module can get access to code from another module by importing the file/function using import. 

Modules refer to a file containing Python statements and definitions. We can define our most used functions in a module and import it, instead of copying their definitions into different program. It is use modules to break down large programs into small manageable and organized files. It provide reusability of code.

1. import module_name

We can import the definitions inside a module to another module or the interactive interpreter in Python.

We can use any Python source file as a module by executing an import statement in some other Python source file. When the interpreter encounters an import statement, it imports the module if the module is present in the search path.

We use the import keyword to import modules in python. When the import is used, it searches for the module initially in the local scope by calling __import__() function. The value returned by the function is then reflected in the output of the initial code.


Syntax:

import module_name

Example:

import math
print(math.pi)

Output: 3.141592653589793

2. import module_name.member_name

We can import specific names from a module without importing the module as a whole.

from math import pi
print(pi)

Output: 3.141592653589793

3. from module_name import *

We can import all names(definitions) from a module using the following construct.

from math import *
print(factorial(7))

Output: 5040

Importing everything with the asterisk (*) symbol is not a good programming practice. It can lead to duplicate definitions for an identifier. It also hampers the readability of our code.

Tags