Module vs Package in Python: Key Differences and Usage
module is a single file containing Python code, while a package is a folder that contains multiple modules and a special __init__.py file to group them. Modules help organize code in one file, and packages organize multiple modules into a directory structure.Quick Comparison
Here is a quick side-by-side comparison of Python modules and packages to understand their main differences.
| Factor | Module | Package |
|---|---|---|
| Definition | A single Python file (.py) with code | A directory with multiple modules and an __init__.py file |
| Structure | One file | Folder containing multiple files and subfolders |
| Purpose | Organize code in one file | Organize related modules together |
| Import style | import module_name | import package_name.module_name |
| Contains | Functions, classes, variables | Multiple modules and sub-packages |
| Example | math.py | numpy/ (folder with many modules) |
Key Differences
A module in Python is simply a file that contains Python code such as functions, classes, or variables. It helps you keep your code organized by splitting it into separate files. You can import a module directly by its filename without the .py extension.
A package is a way to organize multiple related modules into a folder. This folder must contain a special file named __init__.py (which can be empty) to tell Python that this folder is a package. Packages allow you to create a hierarchy of modules and sub-packages, making large projects easier to manage.
When you import a module, you get access to the code inside that single file. When you import from a package, you specify the package and the module inside it, which helps avoid name conflicts and keeps code modular. Packages are essential for distributing libraries and frameworks.
Code Comparison
Here is an example showing how to create and use a simple module in Python.
## mymodule.py def greet(name): return f"Hello, {name}!" # main.py import mymodule print(mymodule.greet('Alice'))
Package Equivalent
Now, the same functionality organized as a package with a module inside it.
# Directory structure: # mypackage/ # ├── __init__.py # └── greetings.py # mypackage/greetings.py def greet(name): return f"Hello, {name}!" # main.py from mypackage import greetings print(greetings.greet('Alice'))
When to Use Which
Choose a module when you have a small set of related functions or classes that fit well in a single file. Modules are perfect for simple scripts or small utilities.
Choose a package when your project grows and you need to organize multiple modules logically. Packages help keep your codebase clean, avoid name clashes, and make it easier to maintain and distribute.