In Python, Modules and Packages are the tools that allow you to organize your code into manageable, reusable pieces. As your project grows from a single script to thousands of lines of code, these structures help you avoid a "spaghetti code" mess.
A Module is simply a file containing Python definitions and statements. Any file ending in .py is a module. It can contain functions, classes, and variables that you can "import" into other scripts.
Why use them? To break down a large program into smaller, logical files.
A Package is a collection of related modules organized in a directory hierarchy.
The __init__.py file: For a folder to be recognized as a package, it traditionally contains a file named __init__.py. This file can be empty, but it tells Python, "Treat this directory as a package."
When you import a module, Python looks for it in:
The current directory.
Built-in modules (like math or os).
The list of directories defined in sys.path (where external libraries are installed).
Imagine you have a file named calculator.py:
# calculator.py def add(a, b): return a + b def subtract(a, b): return a - b version = "1.0"
You can use this module in your main.py file in three ways:
# main.py # Method 1: Import the whole module import calculator print(calculator.add(5, 3)) # Method 2: Import specific functions from calculator import subtract, version print(subtract(10, 5)) print(f"Running version: {version}") # Method 3: Import with an alias (nickname) import calculator as calc print(calc.add(10, 10))
To create a package called my_app, your folder structure should look like this:
my_app/ │ ├── __init__.py ├── database.py └── auth.py
To use a module inside this package:
from my_app import auth from my_app.database import connect_to_db auth.login("admin", "1234")
When you import a module, Python executes all the code in it. If you have test code in your module that you don't want to run when imported, use this block:
def my_function(): print("Function logic here") if __name__ == "__main__": # This only runs if you run this file directly print("Testing my_function...") my_function()
| Structure | Definition | Analogy |
| Module | A single .py file. | A single tool (e.g., a hammer). |
| Package | A folder containing modules and __init__.py. | A toolbox containing many tools. |
| Library | A collection of packages (e.g., NumPy, Pandas). | A whole workshop or hardware store. |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION