Skip to content

Python Packages

Structure multi-file projects with packages, __init__.py, relative imports, and namespace packages.

What you'll learn

  • Create packages with directories and __init__.py
  • Use absolute and relative imports
  • Understand __init__.py and package initialization
  • Structure a project with subpackages
  • Install packages in development mode

Concept

What Is a Package?

A package is a directory containing Python modules. The directory must contain an __init__.py file (which can be empty) to be recognized as a package in traditional Python:

myproject/
├── __init__.py
├── models/
│   ├── __init__.py
│   ├── user.py
│   └── product.py
├── utils/
│   ├── __init__.py
│   ├── strings.py
│   └── files.py
└── main.py

The __init__.py file marks a directory as a package. It can be empty, or it can contain initialization code that runs when the package is imported. In Python 3.3+, namespace packages work without __init__.py, but explicit packages are still recommended for clarity.

The __init__.py File

The __init__.py runs when the package is first imported. You can use it to:

# models/__init__.py
from .user import User
from .product import Product

__all__ = ["User", "Product"]
__version__ = "1.0.0"

This lets users import directly from the package: from models import User instead of from models.user import User. The __init__.py acts as the package's public API.

Absolute Imports

Absolute imports use the full dotted path from the project root:

# main.py
from models.user import User
from utils.strings import capitalize
from utils.files import read_csv

Absolute imports are recommended — they are explicit, clear, and not affected by the importing module's location. PEP 8 explicitly recommends absolute imports.

Relative Imports

Relative imports use dots to navigate relative to the current module's position in the package:

# models/user.py
from . import product        # same package (models)
from ..utils.strings import capitalize  # parent package, then utils
from .product import Product  # specific module in same package
  • . — current package
  • .. — parent package
  • ... — grandparent package

Relative imports are useful within a package but can only be used inside a package (not in the top-level script). They can make refactoring harder because the import meaning depends on the file's location.

Structuring a Project

A well-structured Python project:

myapp/
├── pyproject.toml          # project metadata and dependencies
├── README.md
├── src/
│   └── myapp/              # the actual package
│       ├── __init__.py
│       ├── cli.py          # command-line interface
│       ├── core/
│       │   ├── __init__.py
│       │   ├── calculator.py
│       │   └── parser.py
│       └── utils/
│           ├── __init__.py
│           └── helpers.py
└── tests/
    ├── test_calculator.py
    └── test_parser.py

The src/ layout separates your package from the project root, preventing accidental imports from the working directory during testing. pyproject.toml is the modern standard for project configuration (replacing setup.py).

Installing Your Own Package

To install your own package in development mode (changes are reflected immediately without reinstalling):

pip install -e .

This creates a link to your source code instead of copying it. You can then import your package from anywhere:

import myapp
from myapp.core.calculator import Calculator

The -e (editable) flag is essential during development — it lets you modify your code and test the changes without reinstalling after every edit.

Namespace Packages

Python 3.3+ supports namespace packages — packages split across multiple directories without __init__.py. This is used by large projects that span multiple repositories:

company/
├── billing/        # no __init__.py — namespace package
│   └── invoices.py
└── shipping/       # no __init__.py — namespace package
    └── orders.py

For most projects, traditional packages with __init__.py are clearer and recommended.

Example

              # --- Project structure ---
# myapp/
# ├── __init__.py
# ├── models/
# │   ├── __init__.py
# │   ├── user.py
# │   └── product.py
# ├── utils/
# │   ├── __init__.py
# │   └── helpers.py
# └── main.py

# --- models/__init__.py ---
# from .user import User
# from .product import Product
# __all__ = ["User", "Product"]

# --- models/user.py ---
# class User:
#     def __init__(self, name, email):
#         self.name = name
#         self.email = email
#     def __repr__(self):
#         return f"User({self.name!r})"

# --- main.py using absolute imports ---
# from myapp.models import User, Product
# from myapp.utils.helpers import format_email

# --- Example of __init__.py with version ---
# myapp/__init__.py:
__version__ = "1.2.3"
__author__ = "Ada Lovelace"

# When someone does: import myapp
# They get access to: myapp.__version__, myapp.__author__

# --- Relative imports inside the package ---
# In models/user.py:
# from ..utils.helpers import validate_email  # go up to myapp, then utils
# from .product import Product                # same package (models)

# --- Installing in development mode ---
# $ pip install -e .
# This lets you: import myapp  # from anywhere on the system

# --- Checking package metadata ---
import importlib.metadata
# In Python 3.8+:
# version = importlib.metadata.version("myapp")
# print(version)  # 1.2.3

print("Package structure defines how Python code is organized")
print(f"Version: {__version__}, Author: {__author__}")
            

Shows a project structure with packages and subpackages, __init__.py with re-exports and metadata, absolute and relative import examples, editable install command, and package metadata access.

Try it

  • JSON Formatter

    Package configuration files (pyproject.toml) use structured formats.

  • Case Converter

    Package and module naming — snake_case for modules, snake_case for packages.

Common mistakes

The mistake

Running a script with relative imports directly as python models/user.py

The fix

Relative imports only work when the module is imported as part of a package, not run directly. Use 'python -m myapp.main' to run as a module, or restructure to use absolute imports for the entry point.

The mistake

Forgetting __init__.py and wondering why imports fail

The fix

Without __init__.py (in Python < 3.3), the directory is not a package and imports fail with ModuleNotFoundError. Create an empty __init__.py in every package directory. Python 3.3+ has namespace packages, but explicit __init__.py is still clearer.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors