Modular Programming
What Is a Module?
A module in Python is simply a .py file containing Python code—functions, classes, variables, or runnable statements. Modules enable **code reuse**, **organization**, and **separation of concerns**.
- Each Python file is automatically a module.
- Modules can be imported into other scripts.
- Standard library (e.g.,
math,os) and third-party packages are built from modules. - Modular code is easier to test, debug, and maintain.
Creating Your First Module
Let’s create a module called math_utils.py:
1.
math_utils.py – A Custom Module# math_utils.py
def add(a, b):
"""Return sum of two numbers."""
return a + b
def multiply(a, b):
"""Return product of two numbers."""
return a * b
PI = 3.14159
# This runs only if the file is executed directly
if __name__ == "__main__":
print("Testing module:")
print("2 + 3 =", add(2, 3))
print("2 * 3 =", multiply(2, 3))Importing Modules
Now use this module in another file, e.g., main.py.
2. Basic Import
# main.py
import math_utils
result = math_utils.add(10, 5)
print(result) # 15
print(math_utils.PI) # 3.141593. Import with Alias
import math_utils as mu
print(mu.multiply(4, 7)) # 284. Import Specific Items
from math_utils import add, PI
print(add(1, 2)) # 3
print(PI) # 3.141595. Import All (Use Sparingly!)
from math_utils import *
print(multiply(3, 3)) # 9
# ⚠️ Avoid in large projects—pollutes namespace!The __name__ == "__main__" Guard
This idiom ensures code runs **only when the file is executed directly**, not when imported.
- When you run
python math_utils.py→__name__is"__main__". - When you
import math_utils→__name__is"math_utils".
Use it for **module testing** or **demo code**.
6. Safe Module Execution
# In any module
def main():
print("Running as script!")
if __name__ == "__main__":
main() # Only runs if file is executed directlyPython’s Module Search Path
When you import xyz, Python looks for xyz.py in:
- The current directory
- Directories in
PYTHONPATHenvironment variable - Standard library locations
- Site-packages (for installed packages)
You can view the search path with:
import sys
print(sys.path)7. Adding Custom Paths (Advanced)
import sys
sys.path.append("/path/to/your/modules")
# Now you can import from that directory
import my_custom_moduleStandard Library Modules (Examples)
8. Using
mathimport math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...9. Using
randomfrom random import randint
print(randint(1, 10)) # Random int between 1–1010. Using
os for File Pathsimport os
current = os.getcwd()
print("Current directory:", current)Creating Packages (Multiple Modules)
A package is a directory containing multiple modules and an __init__.py file (can be empty).
my_package/
├── __init__.py
├── math_ops.py
└── string_ops.py11. Import from Package
# Import entire module
from my_package import math_ops
# Import specific function
from my_package.string_ops import reverse_string
# Relative import (inside package)
# from .math_ops import add12.
__init__.py Controls Public API# my_package/__init__.py
from .math_ops import add, multiply
from .string_ops import reverse_string
# Now users can do:
# from my_package import add, reverse_stringBest Practices
- ✅ **Use descriptive module names** (e.g.,
data_validator.py, notutils.py). - ✅ **Avoid
from module import ***—it hides dependencies and causes naming conflicts. - ✅ **Always use
if __name__ == "__main__":** for test/demo code. - ✅ **Group related functions** into logical modules.
- ✅ **Document your modules** with docstrings and comments.
- ✅ **Keep modules focused**—one responsibility per module.
Common Pitfalls
- ❌ Naming your module the same as a standard library module (e.g.,
json.py). - ❌ Circular imports (Module A imports B, and B imports A).
- ❌ Forgetting
__init__.pyin packages (required in Python < 3.3). - ❌ Modifying
sys.pathunnecessarily—use virtual environments instead.
Key Takeaways
- Every
.pyfile is a **module**. - Use
import,from ... import, or aliases to reuse code. - The
__name__ == "__main__"guard enables **dual-use**: importable + executable. - Modular programming = **cleaner, scalable, and professional** code.
- Packages organize **multiple related modules** into a single namespace.