Browse Python Topics โ–ผ
Pick a Web Framework

Packages and Modern Project Structure

๐Ÿ“‚ Modules, Packages & Environments ๐Ÿ“˜ Lesson 39 of 57

Organize complex Python codebases into modular packages with __init__.py, relative vs absolute imports, and the modern src-layout standard.

If a Python module is like a single document or sheet of notes, a Package is a labeled filing folder containing multiple related modules.

As applications grow from simple scripts into real systemsโ€”like web APIs, games, or data pipelinesโ€”you will eventually write dozens of modules:

  • User management (auth.py, profile.py)
  • Billing & Payments (stripe.py, paypal.py, invoices.py)
  • Database connectors (postgres.py, redis.py)

Dumping 60 different .py files into a single root folder produces chaotic clutter. A Package lets you group related modules into clean, hierarchical folders.


1. What Makes a Folder a Package? The __init__.py File

In Python, a directory is recognized as an importable package when it contains a special file named __init__.py:

ecommerce/                # Package folder
โ”œโ”€โ”€ __init__.py           # Package initializer
โ”œโ”€โ”€ cart.py               # Module inside package
โ”œโ”€โ”€ checkout.py           # Module inside package
โ””โ”€โ”€ inventory.py          # Module inside package

The Two Roles of __init__.py:

  1. Package Marker: It tells Pythonโ€™s import engine that this folder should be treated as a Python package.
  2. Package Initializer: When someone writes import ecommerce, Python executes __init__.py automatically!

2. Exposing a Clean Public API

Without thoughtful design, consumers of your package would be forced to navigate deep internal file paths:

# Clumsy, verbose imports:
from ecommerce.billing.processors.stripe_gateway import StripePayment

Inside ecommerce/__init__.py, you can import your key classes and expose them directly at the root of the package:

# ecommerce/__init__.py
"""E-Commerce Core Package."""

from .cart import ShoppingCart
from .checkout import process_payment

# Control what exports when someone types `from ecommerce import *`
__all__ = ["ShoppingCart", "process_payment"]

Now, anyone using your package enjoys a beautiful, effortless import experience:

# Clean and professional!
from ecommerce import ShoppingCart, process_payment

3. Absolute vs Relative Imports

When modules inside the same package need to call one another, you can choose between Absolute and Relative imports:

Specify the complete path starting from the projectโ€™s root package name:

# Inside ecommerce/checkout.py:
from ecommerce.inventory import check_stock
from ecommerce.cart import ShoppingCart

Why itโ€™s preferred: Clear, unambiguous, and easy to search across your codebase.

Relative Imports (Dot Notation)

Reference modules relative to the current fileโ€™s location using leading dots:

  • Single Dot (.): Current package folder.
  • Double Dot (..): Parent directory.
# Inside ecommerce/checkout.py:
from .inventory import check_stock   # Same folder!
from .cart import ShoppingCart       # Same folder!

4. Modern Professional Project Layout: The src/ Layout

When organizing a professional Python repository, where should your files live?

The modern industry standard (recommended by Python packaging authorities and tools like Poetry, Hatch, and Flit) is the src/ layout:

my_awesome_project/
โ”œโ”€โ”€ pyproject.toml              # Project metadata, dependencies, build config
โ”œโ”€โ”€ README.md                   # Human-readable documentation
โ”œโ”€โ”€ .gitignore                  # Git exclusions (.venv, __pycache__)
โ”‚
โ”œโ”€โ”€ src/                        # APPLICATION SOURCE CODE
โ”‚   โ””โ”€โ”€ my_package/             # The actual importable package
โ”‚       โ”œโ”€โ”€ __init__.py         # Package root
โ”‚       โ”œโ”€โ”€ core.py             # Main business logic
โ”‚       โ”œโ”€โ”€ utils.py            # Helper utilities
โ”‚       โ””โ”€โ”€ subpackage/         # Nested sub-package
โ”‚           โ”œโ”€โ”€ __init__.py
โ”‚           โ””โ”€โ”€ helpers.py
โ”‚
โ””โ”€โ”€ tests/                      # AUTOMATED TEST SUITE
    โ”œโ”€โ”€ __init__.py
    โ”œโ”€โ”€ test_core.py            # Unit tests for core.py
    โ””โ”€โ”€ test_utils.py           # Unit tests for utils.py

Why Use the src/ Layout instead of a Flat Layout?

In older โ€œflatโ€ layouts, the my_package/ folder sat directly in the root folder next to tests. This caused a notorious testing bug: when you ran tests, Python would accidentally import your unbuilt, local source files directly from the current working directory, hiding packaging bugs and installation errors!

The src/ layout guarantees that tests run against the truly installed package, preventing deployment surprises!


Summary & Whatโ€™s Next

  • A package is a directory containing modules and an __init__.py file.
  • Use __init__.py to bundle and expose a clean public API for package consumers.
  • Use __all__ to explicitly define allowed exports.
  • Prefer absolute imports for clarity; use relative dots (.) for intra-package references.
  • Structure projects using the modern src/ layout standard.

Now that you know how to build packages, how do you install third-party libraries (like FastAPI, Requests, or Pytest) without polluting your computerโ€™s system Python? Learn the art of isolation in virtual-environments.

Test your understanding of Packages and Modern Project Structure

Quick interactive practice questions with instant feedback.

Take Quiz โ†’