A custom module is a Python file (.py) that contains functions, variables, or classes which can be reused in other programs.
Creating your own modules helps you:
- Organize large programs
- Reuse code easily
- Improve readability
- Build professional projects
STEP 1: CREATE A MODULE FILE
Create a new Python file, for example:
my_module.py
def greet(name):
return "Hello " + namedef add(a, b):
return a + b
This file is now a custom module.
STEP 2: IMPORT THE MODULE
In another Python file (for example main.py):
import my_moduleprint(my_module.greet("Hira"))
print(my_module.add(5, 3))
Both files must be in the same folder.
IMPORT SPECIFIC FUNCTIONS
from my_module import greetprint(greet("Ali"))
Now you donât need to write my_module.greet().
USING ALIAS
import my_module as mmprint(mm.add(10, 20))
Alias makes long names shorter.
ADDING VARIABLES IN MODULE
You can also define variables inside a module.
my_module.py
pi_value = 3.14
Use it like this:
import my_moduleprint(my_module.pi_value)
USING MAIN CHECK (BEST PRACTICE)
To prevent code from running automatically when imported:
def greet():
print("Hello!")if __name__ == "__main__":
greet()
This ensures the function runs only when the file is executed directly.
MODULE SEARCH PATH
Python looks for modules:
- In the current folder
- In system library folders
- In installed packages
You can check path using:
import sys
print(sys.path)
BENEFITS OF CUSTOM MODULES
⢠Code reusability
⢠Better structure
⢠Easier maintenance
⢠Professional project organization
KEY TAKEAWAYS
⢠A module is simply a .py file
⢠Use import module_name to use it
⢠Keep modules in the same directory
⢠Use if __name__ == "__main__" for best practice
Creating custom modules is an important step toward building large and well-structured Python applications.