In Python, a module is defined as a file that contains functions, classes, or variables. It facilitates the logical organization of code and allows for its reuse in various programs. Numerous Python modules exist, each designed for particular tasks.
What is a Module in Python?
A Python module refers to a file that contains Python code (typically, it has a .py extension) which encompasses definitions for functions, classes, or variables. Additionally, a module may contain executable code.
Organizing related code within a module enhances readability, facilitates reuse in different applications, and ensures everything remains systematically arranged.
There are three types of modules in Python:
- User-defined Modules
- Built-in Modules
- Third-Party Modules
Creating a Python Module
To develop a Python module, it is necessary to compose the desired code and store it in a file that has the .py extension.
Python Example to Create a Module
Let us examine a case to illustrate the process of developing a Python module.
Example
# module: calculator.py
# function to add two numbers
def add(a, b):
return a + b
# function to subtract two numbers
def subtract(a, b):
return a - b
# function to multiply two numbers
def multiply(a, b):
return a * b
# function to divide two numbers
def divide(a, b):
return a / b
Explanation:
In the preceding example, a Python script has been developed that includes several functions designed to facilitate the addition, subtraction, multiplication, and division of two numbers. This file has been named calculator.py. This custom module can be utilized in additional Python applications.
Importing Module in Python
In Python, it is possible to bring in the functions and classes from one module into another module or the interactive interpreter. This can be accomplished using the import statement as demonstrated below:
Importing Module Syntax in Python
It has the following syntax:
import module_name
By utilizing the import keyword along with the module_name, we can access the functions that are defined within that module.
Note: Using the import statement, we import the whole module. In order to access the function from the imported module, we need to use the dot . operator.
Python Example for Importing Module
We will examine the subsequent example in which we aim to import the user-created module 'calculator.py' and utilize its functions.
Example
# importing the module
import calculator
# initializing some variables
num_1 = 16
num_2 = 7
# calling the functions of the module
total = calculator.add(num_1, num_2)
diff = calculator.subtract(num_1, num_2)
prod = calculator.multiply(num_1, num_2)
quot = calculator.divide(num_1, num_2)
# printing results
print(num_1, '+', num_2, '=', total)
print(num_1, '-', num_2, '=', diff)
print(num_1, '*', num_2, '=', prod)
print(num_1, '/', num_2, '=', quot)
Output:
16 + 7 = 23
16 - 7 = 9
16 * 7 = 112
16 / 7 = 2.2857142857142856
Explanation:
In this instance, we have brought in the user-defined module 'calculator' and initialized two variables. Subsequently, we have utilized various functions such as add, subtract, multiply, and divide from the 'calculator' module, saving their outcomes in designated variables. Finally, we displayed the results.
Python Import with Renaming
In Python, it is possible to import a module under a different name. This approach enables us to utilize an alias (a more concise reference) for that particular module.
Python Import and Renaming Example
Let us examine the subsequent example for enhanced comprehension.
Example
# importing the module with alias
import calculator as cal
# initializing some variables
num_1 = 25
num_2 = 9
# calling the functions of the module
total = cal.add(num_1, num_2)
diff = cal.subtract(num_1, num_2)
prod = cal.multiply(num_1, num_2)
quot = cal.divide(num_1, num_2)
# printing results
print(num_1, '+', num_2, '=', total)
print(num_1, '-', num_2, '=', diff)
print(num_1, '*', num_2, '=', prod)
print(num_1, '/', num_2, '=', quot)
Output:
25 + 9 = 34
25 - 9 = 16
25 * 9 = 225
25 / 9 = 2.7777777777777777
Explanation:
In the preceding example, we imported the user-defined module 'calculator' under the alias 'cal' and initialized two variables. Subsequently, we invoked various functions such as add, subtract, multiple, and divide from the imported module by using cal followed by the respective function name. The outcomes of these functions were saved in separate variables, which were then printed to display their values.
Python from…import Statement
Python provides the capability to import individual attributes without needing to import the entire module. To illustrate this concept, consider the following example:
Example
# importing certain attributes from the module
from calculator import subtract, multiply
# initializing some variables
num_1 = 12
num_2 = 7
# calling the imported functions
diff = subtract(num_1, num_2)
prod = multiply(num_1, num_2)
# printing results
print(num_1, '-', num_2, '=', diff)
print(num_1, '*', num_2, '=', prod)
Output:
12 - 7 = 5
12 * 7 = 84
Explanation:
In the preceding example, the functions subtract and multiply have been imported from the custom module named 'calculator'. Subsequently, two variables were initialized, and the imported functions were invoked to determine the difference and the product of the given numbers. Finally, the computed values were displayed.
Importing All Attributes
In a manner akin to importing specific attributes from a module, we can utilize the asterisk (*) symbol to import all components from that module.
Syntax:
It has the following syntax:
from module_name import *
Python Example for Importing All Attributes
Here is an example showing the same:
Example
# importing everything from the module
from calculator import *
# initializing some variables
num_1 = 19
num_2 = 14
# calling the imported functions
prod = multiply(num_1, num_2)
quot = divide(num_1, num_2)
# printing results
print(num_1, '*', num_2, '=', prod)
print(num_1, '/', num_2, '=', quot)
Output:
19 * 14 = 266
19 / 14 = 1.3571428571428572
Explanation:
In this instance, we have brought in all components from the user-created module 'calculator' by utilizing the asterisk (*) symbol. Subsequently, we initialized two variables and invoked the multiply and divide functions to compute the product and quotient of the numbers. Finally, we displayed the resulting values.
Locating Python Modules
Each time a module is imported into a program, the Python interpreter searches in various locations. Initially, it verifies if the module is a built-in one; if it is not, the interpreter then examines the directories outlined in sys.path. The search process for the module by the Python interpreter occurs as follows:
Step 1: Initially, it looks for the module within the current directory.
Step 2: If the module cannot be located in the present directory, Python proceeds to search through each directory listed in the shell variable, PYTHONPATH. This environment variable consists of a series of directory paths.
Step 3: If the module cannot be located, Python examines the list of directories that are dependent on the installation, which were set up during the installation of Python.
To verify the collection of directories, we can utilize the path variable from the sys module as demonstrated below:
Example
# importing the sys module
import sys
# using the 'path' variable from the sys module
print(sys.path)
Output:
['/content', '/env/python', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '', '/usr/local/lib/python3.11/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.11/dist-packages/IPython/extensions', '/usr/local/lib/python3.11/dist-packages/setuptools/_vendor', '/root/.ipython']
Explanation:
In the preceding example, the sys module has been imported, and its path variable has been utilized to retrieve the list of directories containing the modules.
Built-in dir Function
Python provides a built-in function known as dir that assists in enumerating all attribute names (functions, classes, variables) present within a module. For instance, previously, we created several functions such as add, subtract, multiply, and divide in the 'calculator' module. We can utilize the dir function to retrieve information about these attributes in the following way:
Example
# importing the user-defined module
import calculator
# listing all the attributes from the module
print(dir(calculator))
Output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'divide', 'multiply', 'subtract']
Explanation:
In the previously mentioned example, we imported the custom module 'calculator' and utilized the dir function to display all the attributes present in the imported module.
Consequently, we observe a collection of user-defined functions such as add, divide, multiply, and subtract within the 'calculator' module. Any other identifiers that begin with an underscore represent built-in Python attributes associated with the module (as opposed to being user-defined). For instance, the name attribute retains the module's name.
Python Built-in Modules
Python includes numerous built-in modules that provide a wide array of impressive functions and features suited for various tasks. The import statement allows us to incorporate these modules into our project at any time.
Different Examples for Python Built-in Modules
Let us examine several examples that illustrate the process of importing and utilizing the built-in modules in Python.
Example 1: Importing the built-in math Module
In this instance, we will examine the process of importing the math module and explore the application of several of its attributes and functions.
Example
# importing the math module
import math
# using the variables and functions from the imported module
print("Pi =", math.pi) # returns value of Pi
print("Square root of 16 =", math.sqrt(16)) # returns square root of 16
print("Floor value of 19.5 =", math.floor(19.5)) # returns floor value of 19.5
print("Ceiling value of 24.7 =", math.ceil(24.7)) # returns ceiling value of 24.7
print("Factorial of 6 =", math.factorial(6)) # returns factorial of 6
Output:
Pi = 3.141592653589793
Square root of 16 = 4.0
Floor value of 19.5 = 19
Ceiling value of 24.7 = 25
Factorial of 6 = 720
Explanation:
In the preceding example, the math module has been imported. Various variables and functions from the math module have been utilized.
Example 2: Importing the built-in random Module
In this section, we will explore the process of importing the random module and examine the application of several of its functions.
Example
# importing the random module
import random
# given list
list_1 = [1, 4, True, 800, "python", 27, "hello"]
# using the functions from the imported modules
print("Random Integer between 10 and 50 =", random.randint(10, 50)) # returns a random integer between 10 and 50
print("Random Floating Point between 0 and 1 =", random.random()) # returns a floating point between 0 and 1
print("Random Item from the List =", random.choice(list_1)) # returns a random item from the list
Output:
Random Integer between 10 and 50 = 48
Random Floating Point between 0 and 1 = 0.9739271518285192
Random Item from the List = 4
Explanation:
In the preceding illustration, the random module has been imported. We have utilized various variables and functions from the random module.
Conclusion
In this guide, we explored the concept of a Python module. We discovered that a module is essentially a file that holds definitions for functions, classes, or variables, which aids in structuring the code logically and facilitates reuse in various applications. Python utilizes three categories of modules: User-defined, Built-in, and Third-party modules.
We also explored the process of creating and importing a module in Python. We discovered that there are various methods to import and utilize the functions provided by the modules. Finally, we gained insight into how to find modules in Python and the application of the built-in dir function.
Python Modules MCQs
- What is a Python module?
- A special type of Python function
- A file containing Python code like functions, classes, or variables
- A directory with multiple Python files
- A built-in Python keyword
- Which of the following statements is correct to import specific functions from a module?
- import calculator: add, subtract
- from calculator import add, subtract
- import add, subtract from calculator
- calculator import add, subtract
Response: b) from calculator import add, subtract
- What action will the subsequent statement perform?
import calculator as cal
- Imports the calculator module using an alias cal
- Imports all built-in functions from Python
- Creates a new module named cal
- Exports the calculator module as cal
- Which function is used to list all attributes (functions, variables, etc.) of a module?
- list
- inspect
- dir
- attributes
- In which order does Python search for a module when it is imported?
- Installed packages -> PYTHONPATH -> Current directory
- Current directory -> PYTHONPATH -> Built-in modules
- Built-in modules -> PYTHONPATH -> Current directory
- Current directory -> PYTHONPATH -> Installation-dependent directories
Response: d) Active directory -> PYTHONPATH -> Directories dependent on installation