16. Modules and Packages in Python
What Are Modules?
A module in Python is simply a file that contains Python code such as variables, functions, or classes. Modules help you organize code into logical sections and enable code reuse.
# greetings.py (this is a module)
def say_hello(name):
return f"Hello, {name}!"
# main.py
import greetings
print(greetings.say_hello("Alice"))Importing Modules
You can import an entire module or specific functions from it. You can also rename modules for convenience using aliases.
import math
print(math.sqrt(16))
from math import pi, sqrt
print(pi, sqrt(25))
import math as m
print(m.factorial(5))What Are Packages?
A package is a directory that contains multiple modules. Packages make it easier to build large applications by organizing related modules together.
my_app/
āāā __init__.py
āāā utils.py
āāā math_tools/
ā āāā __init__.py
ā āāā calculator.pyThe presence of an `__init__.py` file makes a directory a Python package.
Importing from Packages
# math_tools/calculator.py
def add(a, b):
return a + b
# main.py
from math_tools.calculator import add
print(add(3, 7))Absolute vs Relative Imports
Within packages, you can import modules using either absolute or relative imports.
# Absolute import
from my_app.utils import format_name
# Relative import (inside package)
from .utils import format_name
from ..helpers import loggerThe Python Module Search Path
When you import a module, Python searches for it in a specific order:
- Current directory
- PYTHONPATH directories
- Installed site-packages
import sys
print(sys.path) # Shows where Python looks for modulesUnderstanding Python Imports in Depth
Mini Project Step
Refactor your growing Calculator project: split your code into modules like `operations.py` and `history.py`, then group them into a package called `calculator_app`.