01 / 20

Organizing Modules
& Packages

Learn to structure your Python code into reusable modules and organized packages using the __init__.py convention.

Python

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.

math_helpers.py
A module with utility functions for calculations
validators.py
A module with input validation logic

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.

mypackage/ __init__.py module_a.py module_b.py A package is a folder with __init__.py + modules

Why Organize Your Code?

Reusability
Write a function once, import it anywhere across your project
Readability
Small, focused files are easier to read and understand
Maintainability
Fix bugs in one module without touching unrelated 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.

1
Package marker: Without it (in older Python), the folder is just a regular directory, not an importable package.
2
Initialization code: You can run setup logic (configure logging, set defaults) when the package is first imported.
3
Control exports: Define __all__ to specify which names are public when someone uses from package import *.

The Core Rule

my_folder/ utils.py helpers.py ✕ Not importable → my_package/ __init__.py utils.py, helpers.py ✓ Importable package

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

import module
Imports the entire module. Access via module.func().
from module import func
Imports a specific name. Use directly as func().
from package import module
Imports a module from inside a package by name.

How to Create a Package

1
Create a directory with a descriptive name (e.g., analytics).
2
Add __init__.py inside the directory. It can be empty or contain initialization code.
3
Create module files (.py) inside the directory with related functionality.
4
Import from your package: use from analytics import stats in other files.
5
(Optional) Define __all__ in __init__.py to control public exports.

Example 1: A Simple Module

# file: greetings.py def say_hello(name): return f"Hello, {name}!" def say_goodbye(name): return f"Goodbye, {name}!"
# file: main.py import greetings print(greetings.say_hello("Alice")) # Output: Hello, Alice!

Example 2: Building a Package

project/ main.py utils/ __init__.py strings.py numbers.py # utils/__init__.py from .strings import capitalize from .numbers import double # main.py from utils import capitalize print (capitalize( "hello" )) # Output: Hello

Example 3: Nested Packages

app/ __init__.py models/ __init__.py user.py product.py views/ __init__.py dashboard.py # Importing from nested packages from app.models.user import User Every sub-directory needs its own __init__.py

Controlling Exports with __all__

The __all__ variable is a list of strings that defines which names are exported when someone writes from package import *.

# utils/__init__.py from .strings import capitalize, lowercase from .numbers import double, triple __all__ = ["capitalize", "double"] # Only capitalize and double are exported by *

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

✕ Missing __init__.py
Forgetting to add __init__.py means Python won't recognize the folder as a package. You get a ModuleNotFoundError.
✕ Circular Imports
Module A imports B, and B imports A. Python raises ImportError. Fix by restructuring or using lazy imports.
✕ Name Shadowing
Naming your file math.py shadows the built-in math module. Python imports your file instead of the standard library.

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?

myapp/ __init__.py hello.py # contains def greet(): ...

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?