A module in Python is a file containing Python code such as functions, variables, classes, and statements. Modules help us organize code and reuse it in different programs.
.py file that can be imported
and used in another Python program.
A module is a Python file that contains reusable code. Instead of writing the same code again and again, we can place it inside a module and import it whenever we need it.
For example, a file named:
calculator.py
can contain calculator functions that can be used by other Python programs.
To create a module, simply create a Python file with the
.py extension.
For example, create a file named:
calculator.py
Add the following code:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
The file calculator.py is now a module.
We can use the import keyword to import a module.
import calculator
print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
The import statement loads a module so that its contents can
be used in the current program.
import math
print(math.sqrt(25))
After importing a module, we can access its functions using the dot operator.
import calculator
result = calculator.add(20, 30)
print(result)
We can import a specific function from a module using
from ... import.
from calculator import add
print(add(10, 20))
Now we can call add() directly without writing
calculator.add().
We can import more than one function from a module.
from calculator import add, subtract
print(add(20, 10))
print(subtract(20, 10))
The * symbol can be used to import names from a module.
from calculator import *
print(add(5, 5))
print(subtract(10, 4))
from module import * can make it less clear where
a name came from. Explicit imports are generally easier to read.
We can give a module a shorter name using the as keyword.
import math as m
print(m.sqrt(36))
We can also give an imported function another name.
from math import sqrt as square_root
print(square_root(49))
Python provides many modules as part of its standard library. Some commonly used modules are:
| Module | Purpose |
|---|---|
| math | Mathematical functions |
| random | Generate random values |
| datetime | Work with dates and times |
| os | Interact with the operating system |
| json | Work with JSON data |
| re | Regular expressions |
The math module provides many mathematical functions.
import math
print(math.sqrt(64))
print(math.factorial(5))
print(math.pi)
The random module provides functions for generating
pseudo-random values.
import random
number = random.randint(1, 10)
print(number)
The output will be an integer between 1 and 10.
The datetime module is used for working with dates and times.
import datetime
today = datetime.date.today()
print(today)
The exact output depends on the date when the program runs.
The os module provides functions for interacting with
the operating system.
import os
print(os.getcwd())
This displays the current working directory.
A module can contain variables in addition to functions.
For example, student.py:
name = "Rahul"
age = 20
Another program can use these variables:
import student
print(student.name)
print(student.age)
A module can also contain classes.
class Student:
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
If this code is saved in student.py, it can be imported
into another Python program.
from student import Student
s = Student("Amit")
s.show()
Python provides the special variable __name__.
When a Python file is run directly, its value is usually
"__main__".
def welcome():
print("Welcome to Python")
if __name__ == "__main__":
welcome()
This pattern allows code to run when the file is executed directly, while preventing that block from running just because the module is imported.
When Python imports a module, it searches for that module in locations available through Python's module search path.
The search path can be inspected using sys.path.
import sys
print(sys.path)
It displays a list of directories that Python searches when importing modules.
Suppose we have two files in the same folder.
File 1: calculator.py
def add(a, b):
return a + b
File 2: main.py
import calculator
result = calculator.add(100, 50)
print(result)
A module file normally has the .py extension.
It is useful to choose a meaningful module name.
Examples:
calculator.py
student.py
database.py
employees.py
utilities.py
| Function | Module |
|---|---|
| A reusable block of code. | A Python file containing reusable code. |
Created using def. |
Usually stored in a .py file. |
| Performs a specific task. | Can contain functions, classes, variables and other code. |
A module is generally a single Python file, while a package is a way of organizing related Python modules into a directory structure.
calculator.pyPackages are covered in the next lesson.
import keyword is used to import modules.from ... import can be used to import specific names.as keyword can create an alias.Question: Which keyword is used to import a Python module?