Organizing Modules
& Packages
Learn to structure your Python code into reusable modules and organized packages using the __init__.py convention.
What Is a Module?
A module is simply a single .py file containing Python definitions: functions, classes, and variables. Every Python file you create is already a module.
What Is a Package?
A package is a directory (folder) that contains one or more modules, plus a special file called __init__.py. Packages let you group related modules under a single namespace.
Why Organize Your Code?
The Role of __init__.py
The __init__.py file tells Python that a directory should be treated as a package. It runs automatically when the package is imported.
The Core Rule
Module vs Package
| Module | Package | |
|---|---|---|
| What is it? | A single .py file | A directory of modules |
| Contains | Functions, classes, variables | Modules + __init__.py |
| Import syntax | import utils | from pkg import utils |
| Nesting | Cannot nest | Can contain sub-packages |
| Example | math, os, sys | json, email, urllib |
Import Mechanisms
How to Create a Package
Example 1: A Simple Module
Example 2: Building a Package
Example 3: Nested Packages
Controlling Exports with __all__
The __all__ variable is a list of strings that defines which names are exported when someone writes from package import *.
Absolute vs Relative Imports
| Absolute Import | Relative Import | |
|---|---|---|
| Syntax | from app.models import user | from .models import user |
| The dot (.) | Not used | Means "current package" |
| Clarity | Full path is always explicit | Shorter, but context-dependent |
| Best for | Top-level scripts, most code | Within the same package |
Common Mistakes
Summary Reference
| Concept | Key Detail | Example |
|---|---|---|
| Module | A single .py file | helpers.py |
| Package | Directory + __init__.py | utils/ |
| __init__.py | Marks dir as package; runs on import | Can be empty |
| __all__ | Controls * exports | ["func_a", "ClassB"] |
| Relative import | Uses dots for current package | from . import x |
| Sub-package | Package inside a package | app.models.user |
Question 1 of 5
What file must be present in a directory for Python to treat it as a package?
Question 2 of 5
Given this structure, what is the correct import statement to use greet() from hello.py?
Question 3 of 5
What does the __all__ variable in __init__.py control?
Question 4 of 5
You named your file random.py and wrote import random. Your code crashes. What happened?
Question 5 of 5
In a relative import, what does from . import helpers mean?