Modules in Python
In this tutorial, we will learn modules in Python, which we can invoke into any program to perform different tasks. So, let’s first understand what is a module.
A module in Python is a file which contains a collection of related Python statements and definitions. In simple words, it is basically a file that contains a piece of Python code we like. It allows us to logically organize our Python code.
For instance, database related code is put inside a database module, security code in a security module, etc. Thus, grouping related code in a module makes the code easier to understand and usage.
Any file that contains proper Python code and has the .py extension is a module. The name of file is module name. For example, if the file name is Test.py, Test is the name of module. By convention, module name should be short and all lower-case. We can optionally use an underscore to improve readability.
A module is known by its main filename without the .py extension. For example, create a module and save it as addition.py.
def add(x, y):
s = x + y
return s
This module will be known as addition. All the Python programs that we have written so far with .py extension are modules as well as programs. The main difference is that programs are created to be executed, whereas module are built up to be imported and used by the programs.
A module usually contains statements, variables, functions, classes, files, and attributes that we can bind and reference. It can also contain runnable code. We can easily access these objects by importing them.
Why should Create Multiple Modules in a Program?
There are two reasons why should we create multiple modules in a program. They are as follows:
(1) A smaller program can have a few lines of code. As our program file grows up, it may contain multiple lines of code. Instead of putting everything in a single program, we should split a big program into multiple modules as per their functionality. It makes our code organized and easier to maintain.
(2) Modules promote the reusing of existing code. For example, we may need a set of handy functions in many programs. Instead of copying these functions in different program, we should put them into a single file and use them by importing in different programs.
Built-in Modules in Python
There are several standard modules available in Python Standard Library that are installed when we install Python. These modules are commonly known as built-in modules. A list of various built-in modules in Python Standard Library is as:
- abc
- aifc
- array
- bisect
- calendar
- cgi
- cmath
- cmd
- code
- collections
- copy
- datetime
- http
- math
- json
- operator
- random, and many more.
You can see the full list of Python standard modules in the lib directory inside the location where you have installed Python.
Creating Custom Modules in Python
We can define the most frequently used functions in one module, and import them in other programs instead of copying their code into different programs. Let’s create a module in Python for finding the multiplication of three numbers. Type the code and save it as multiplier.py.
Example 1:
# Python module example.
"""This program multiplies three numbers
and returns the result"""
# Creating a user-defined function.
def multiply(x, y, z):
result = x * y * z
return result
In this example, we have created a module that contains a function named multiply(). The function takes three numbers and returns the result.
How to Import Module in Python?
In Python, we can use any source file as a module by executing an import statement in another source file or module. Importing a module enables us to access the statements, definition, and objects it contains. The general syntax to use user-defined or custom module in a program file is as:
# This statement imports one module.
import <module_name>
# This statement imports many modules.
import <module_name_1>, <module_name_2>, . . . . , <module_name_N>In the above syntax, import is a keyword. When the Python interpreter (or translator) executes an import statement, it imports the module if the module is available in search path.
A search path is a list of directories the interpreter searches before importing a module. Make sure the import file is present in the native directory. For example, if we reuse the above multiplier user-defined module, then we have to put the following statement at the top of the script code.
Example 2:
import multiplier
print(multiplier.multiply(2, 3, 5))
Output:
30
When we execute the above code, we will get the result 30. In this example, import multiplier imports the module multiplier and creates a reference to that module in the current namespace. Once the module loaded, we have called the function object defined in the module by using the dot operator. The general syntax is as:
module_name.object_name
For example:
module_name.variable
module_name.func()With this syntax, we can easily access the members of a module in a Python program. Let’s take a very simple example based on it.
Let us create a module (i.e. Python file) in Python for finding the addition, subtraction, multiplication, and division of two numbers. Type the following code and save it as Calculator.py.
Example 3:
# Creating a module with a variable and four function definitions.
a = 20
def add(x, y):
s = x + y
return s
def sub(x, y):
if(x > y):
s = x - y
else:
s = y - x
return s
def mul(x, y):
s = x * y
return s
def div(x, y):
if(y == 0):
print("Division error")
return
s = x / y
return s
In this module, we have created a variable with a value. Then, we have created four functions that have two parameters named x and y. We have used a return statement to return a value or values into the calling program.
If you return more than one value, then use a comma separator in between values. The return statement allows us to end the execution of a function before we reach the end.
Now we will create another program file in which we will access the members of a module named Calculator by importing it.
# Importing module.
import Calculator
# Taking two numbers as input from the user.
n1 = int(input("Enter your first number: "))
n2 = int(input("Enter your second number: "))
# Accessing members from a module by importing it.
print("Value of a: ", Calculator.a)
print("Sum: ", Calculator.add(n1, n2))
print("Difference: ", Calculator.sub(n1, n2))
print("Multiplication: ", Calculator.mul(n1, n2))
print("Division: ", Calculator.div(n1, n2))
Output:
Enter your first number: 20
Enter your second number: 10
Value of a: 20
Sum: 30
Difference: 10
Multiplication: 200
Division: 2.0
Note:
(a) Remember that a module is loaded only once, regardless of the number of times it is imported. It prevents the execution of module from occurrence over and over if more than one import take places.
(b) If multiple modules in an application import a given module, it shares a single copy of that module. For instance, if modules X and Y both import a module Z, X and Y share a single copy of the module Z.
(c) If you import two or more modules having the same name , then the name of last module will replace the name of the previous module in the list.
Importing Built-in Math Module
Python provides several standard modules that we can import them the same way as we have imported our user-defined module in the previous section. Let’s take a simple example program in which we will import the most important built-in math module in the program.
Example 4:
# Importing the math module to access members of it.
import math
print("Value of pi = ", math.pi)
x = 16
print("Square root of 16 = ", math.sqrt(x))
y = 5
print("Factorial of 27 = ", math.factorial(y))
Output:
Value of pi = 3.141592653589793
Square root of 16 = 4.0
Factorial of 27 = 120
Importing Module as an Alternate Name (Module Aliasing)
We can also import an entire built-in or user-defined module under an alternate name or with an alias name. The general syntax is as:
import <module_name> as <alt_name>
Let’s take a very simple example in which we will import a math module using an alias name.
Example 5:
# Importing the math module using an alias name ma.
import math as ma
# Accessing members of math module using an alias name ma.
print("Value of pi = ", ma.pi)
x = 25
print("Square root of 25 = ", ma.sqrt(x))
Output:
Value of pi = 3.141592653589793
Square root of 25 = 5.0
In this example, we have renamed the math module as ma. It saves typing time in some cases. Note that math.pi is invalid in this case. ma.pi is correct implementation.
from import Statement in Python
We can import specific attributes from a module without importing the whole module in the current namespace. For example, a math module contains a lot of built-in functions. If we need to import only the pi function, we can use the from…import statement provided by Python.
The from…import has the following general syntax that is as follows:
from <module_name> import <atr_name1>, <atr_name2>, . . . , <atr_nameN>
Let’s take a very simple example program in which we will import only pi attribute from the math module.
Example 6:
# Importing only pi attribute from the math module.
from math import pi
print("Value of pi = ", pi)
Output:
Value of pi = 3.141592653589793
In this example, we have imported only the pi function from the math module. Hence, no need to use the dot operator as we have used in the previous example.
Similarly, we can also import multiple attributes from a module using from…import statement. Let’s take an example in which we will import sqrt(), log10() as well as factorial() from the math module using from…import statement.
Example 7:
# Importing multiple attributes from the math module.
from math import sqrt, log10, factorial
x = 25
y = 10
z = 5
print("Square root of 25 = ", sqrt(x))
print("Value of log10(10) = ", log10(y))
print("Factorial of 5 = ", factorial(z))
Output:
Square root of 25 = 5.0
Value of log10(10) = 1.0
Factorial of 5 = 120
Importing All Names
We can also import all names (definitions or objects) from a module into the current namespace using the following syntax.
from <module_name> import *
Here, the symbol (*) means to import all objects from a module into a calling program. Let’s take an example in which we will import all definitions from a module using the above syntax.
Example 8:
# Importing all objects from the math module.
from math import *
x = 625
y = 3
print("Square root of 625= ", sqrt(x))
print("Factorial of 10 = ", factorial(y))
Output:
Square root of 625= 25.0
Factorial of 10 = 6
In this example, we have imported all the functions from the math module into a program. But, we have used only two sqrt() and factorial() function from the module math. Importing everything using the symbol (*) is not good programming practice for you. It also reduces the readability of your code.
Locating Modules in Python
When we import a module called “multiplier”, the Python interpreter searches for the module in the following sequence.
(1) Interpreter first searches for a built-in module with that name.
(2) If such a module is not found, it then will search for it in the list of directories given by the variable sys.path. It is a basically list of strings that indicates the search path for modules.
The sys.path variables contains current working directory, directory names specified in the PYTHONPATH environment variable and some additional installation dependent directories. The syntax of PYTHONPATH is similar to the shell variable path.
(3) If such a module is not found, the interpreter generates an exception named ImportError.
Different Ways to Import a Module in Python
In this section, we have listed the different ways to import a module in Python. They are:
- import module_name
- import module_name1, module_name2, module_name3, ….
- import module_name as alt_name
- import module_name1 as alt_name1, module_name2 as alt_name2, . . .
- from module_name import member
- from module_name import member1, member2, . . .
- from module_name import member1 as alt_name1
In this tutorial, we have explained about modules in Python through various examples. Hope that you will have understood how to import a module in a program file. In the next, we will discuss the concepts of namespace and scope in Python with the help of examples.
Thanks for reading!!!





