When writing Python programs, you may notice that some code gets repeated again and again. Instead of copying the same code into every file, Python provides modules to help organize and reuse your code.
In this blog, you'll learn what a Python module is, why it's useful, and how to create and use your own modules.
What is a Python Module?
A module is simply a Python file (.py) that contains Python code such as:
- Functions
- Variables
- Classes
You can import a module into another Python file and use its contents without rewriting the code.
For example:
import math
print(math.sqrt(25))
Output:
5.0
Here, math is a built-in Python module.
Why Use Modules?
Modules make programming easier because they:
- Reuse code instead of rewriting it.
- Keep programs organized.
- Make debugging easier.
- Improve readability.
- Allow developers to share code.
Built-in Modules
Python comes with many built-in modules.
math
import math
print(math.pi)
print(math.factorial(5))
Output:
3.141592653589793
120
random
import random
print(random.randint(1, 10))
This generates a random number between 1 and 10.
datetime
import datetime
today = datetime.datetime.now()
print(today)
This displays the current date and time.
Creating Your Own Module
Suppose you create a file named calculator.py.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Now create another file named main.py.
import calculator
print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
Output:
15
5
Your own module works just like Python's built-in modules.
Different Ways to Import Modules
1. Import the entire module
import math
print(math.sqrt(16))
2. Import specific functions
from math import sqrt
print(sqrt(16))
3. Import with an alias
import math as m
print(m.pi)
Aliases make code shorter and easier to read.
The dir() Function
The dir() function displays everything inside a module.
import math
print(dir(math))
This helps you discover available functions and constants.
Module Search Path
When Python imports a module, it searches in the following order:
- Current project folder
- Installed Python packages
- Python's standard library
If Python cannot find the module, it raises a ModuleNotFoundError.
Best Practices
- Give modules meaningful names.
- Keep each module focused on one purpose.
- Avoid duplicate code.
- Group related functions together.
- Use comments and documentation where needed.
Advantages of Modules
- Better code organization
- Easy maintenance
- Code reusability
- Faster development
- Improved readability
- Easier collaboration with teams
Conclusion
Python modules are one of the most powerful features of the language. They help you organize your code into smaller, reusable pieces, making programs cleaner and easier to maintain.
Top comments (0)