Creating Custom Modules
-
Learn how to create your own Python modules to structure projects and reuse code efficiently.
What is a Custom Module?
A custom module is a user-defined Python file (.py) that contains:
Functions
Variables
Classes
Instead of writing the same code again and again, we reuse code by creating modules.
Why Do We Create Custom Modules?
Code reusability
Better organization
Easy maintenance
Clean & readable programs
Professional project structure
Creating a .py Module
Any Python file can act as a module.
Example File Structure:
project/
│
├── main.py
└── calculator.py
1.Creating a Custom Module
Step 1: Create a Module File
Create a file named calculator.py
Creating a Custom Module
This module contains basic arithmetic functions.
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
pi = 3.14
2. Importing Custom Modules
Method 1: Import Entire Module
Syntax
import module_name
Importing Entire Module
This program imports the full module and accesses its functions.
# main.py
import calculator
print(calculator.add(10, 5))
print(calculator.pi)
Method 2: Import Specific Functions
Syntax
from module_name import function_name
Importing Specific Functions
This program imports only selected functions from the module.
from calculator import add, subtract
print(add(8, 3))
print(subtract(10, 4))
Method 3: Import with Alias
Syntax
import module_name as alias
Using Alias for Module
This program imports module using a short name.
import calculator as calc
print(calc.add(6, 2))
Method 4: Import Everything (Not Recommended)
Syntax
from module_name import *
Importing All Module Contents
Imports all functions and variables (may cause confusion).
from calculator import *
print(add(4, 4))
print(pi)