Agent Context · Add file · llms.txt

Python Project Architecture Spec

Purpose: Agent context for structuring, extending, or refactoring a Python project. Scope: Generic. Applies to apps, services, and libraries unless noted. Verified against: PyPA Packaging User Guide, Architecture Patterns with Python (Cosmic Python), zhanymkanov/fastapi-best-practices, Real Python.


1. Top-Level Layout

Choose the layout by project type:

Layout Use for Notes
src/ layout Libraries, CLI tools, anything built, installed, or published Requires an install (editable for development) to run. Prevents accidental imports of the in-development copy from the repo root.
Flat layout Applications run directly from the repo (e.g. via uv run) that are never packaged Simpler; no build step.

If uncertain, use src/.

<repo_root>/
├── pyproject.toml        # single source of project metadata, deps, tool config
├── README.md             # what the project does AND how it is organized
├── .env.example          # documented env vars, no secrets
├── src/                  # omit this level for flat layout
│   └── <package_name>/   # exactly one top-level package
│       ├── __init__.py
│       ├── main.py       # entrypoint / composition root
│       ├── config.py     # settings loaded from environment
│       └── ...           # see section 2
└── tests/                # mirrors <package_name>/ structure

Rules (both layouts):


2. Internal Structure: Choose One Pattern

Pick one pattern based on size and complexity, and apply it consistently.

2A. Layered (by file type): microservices / few feature scopes

<package_name>/
├── api/            # I/O boundary: HTTP routes, CLI commands, message handlers
├── services/       # business logic and use cases
├── repositories/   # data access: DB, external APIs, files
├── models/         # domain entities and schemas
├── core/           # shared utilities, exceptions, logging setup
└── config.py

2B. Feature-First (by domain): apps with many feature scopes

<package_name>/
├── <feature_a>/
│   ├── api.py           # thin handlers only
│   ├── service.py       # business logic
│   ├── repository.py    # data access
│   ├── models.py        # feature entities and schemas
│   ├── config.py        # optional per-feature settings
│   ├── exceptions.py    # feature-specific exceptions
│   └── __init__.py      # public API via __all__
├── <feature_b>/
│   └── ...
├── shared/              # cross-feature code ONLY when truly shared
├── config.py            # global settings
└── main.py

2C. Clean / Hexagonal: complex business domains, many integrations

<package_name>/
├── domain/          # entities, value objects, business rules. NO framework/infra imports.
├── application/     # use cases (service layer); defines ports (interfaces/Protocols)
├── infrastructure/  # adapters implementing ports: DB/ORM, HTTP clients, queues
├── interfaces/      # entrypoints: web routes, CLI, workers
└── main.py          # composition root / bootstrap: wires adapters to ports

Optional for 2C: a Unit of Work to represent atomic updates across repositories.


3. Layer Responsibilities

Layer Does Does not
API / Interfaces Parse input, validate, call a service or use case, format output Business logic, direct DB access
Services / Application Business rules, orchestration, use-case boundaries Depend on concrete infrastructure (depends on abstractions/Protocols)
Repositories / Infrastructure Persistence and external integrations Make business decisions
Models / Domain Entities and business invariants Depend on outer layers, frameworks, or the ORM

4. Dependency Rules (Non-Negotiable)


5. Module Conventions


6. Testing

tests/
├── unit/          # mirrors <package_name>/; no I/O; fake repositories/ports
├── integration/   # real DB / external adapters
└── conftest.py    # shared fixtures

7. Pattern Selection Guide

Project type Layout + Pattern
Script / app run directly, never packaged Flat layout; adopt 2A if it grows
Library or distributable CLI src/ + minimal public API via __all__
Microservice / few feature scopes 2A Layered (by file type is fine)
App with many feature scopes 2B Feature-first (by domain)
Complex domain, many integrations 2C Clean / Hexagonal

8. Agent Instructions


References