Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What Are Modules?
  • - Importing Modules
  • - What Are Packages?
  • - Importing from Packages
  • - Absolute vs Relative Imports
  • - The Python Module Search Path
  • - Mini Project Step

16. Modules and Packages in Python

Level: AdvancedDuration: 35m

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.

python
# greetings.py (this is a module)
def say_hello(name):
    return f"Hello, {name}!"

# main.py
import greetings
print(greetings.say_hello("Alice"))
šŸ’” Any Python file (ending in .py) is considered a module.

Importing Modules

You can import an entire module or specific functions from it. You can also rename modules for convenience using aliases.

python
import math
print(math.sqrt(16))

from math import pi, sqrt
print(pi, sqrt(25))

import math as m
print(m.factorial(5))
šŸ’” Best practice: avoid `from module import *` because it pollutes your namespace and makes debugging harder.

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.

plaintext
my_app/
ā”œā”€ā”€ __init__.py
ā”œā”€ā”€ utils.py
ā”œā”€ā”€ math_tools/
│   ā”œā”€ā”€ __init__.py
│   └── calculator.py

The presence of an `__init__.py` file makes a directory a Python package.

Importing from Packages

python
# 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.

python
# Absolute import
from my_app.utils import format_name

# Relative import (inside package)
from .utils import format_name
from ..helpers import logger
šŸ’” Relative imports use dots to refer to package hierarchy. Use them only within packages, not in standalone scripts.

The Python Module Search Path

When you import a module, Python searches for it in a specific order:

  • Current directory
  • PYTHONPATH directories
  • Installed site-packages
python
import sys
print(sys.path)  # Shows where Python looks for modules

Understanding 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`.