What is the difference between a module and a package in Python?
Short answer
A module is a single .py file containing Python definitions and statements that can be imported.
Advertisement
AModel answer
A module is a single .py file containing Python definitions and statements that can be imported. A package is a directory containing multiple modules plus an __init__.py file (making it importable as a namespace), allowing related modules to be organized hierarchically, e.g., `import package.module`.
# mymodule.py is a module
import mymodule
# mypackage/ with __init__.py is a package
import mypackage.submoduleReal-world example
A web application's codebase organizes routes.py, models.py, and utils.py as modules inside an `app` package, giving a clean `from app.models import User` import path.
Likely follow-ups
- Do packages require __init__.py in modern Python?
- What is a namespace package?
Related topics