Structuring Large Python Projects for Long-Term Maintenance
You’ve joined a five-year-old Python project. Imports loop back on themselves, every folder has a utils.py, and adding one feature means touching five unrelated modules. The code works — barely — but it’s fragile.
The problem isn’t the functions. It’s the structure that never grew up with the project.
By the end of this article, you’ll know how to design and evolve large Python codebases so they stay understandable, testable, and safe to change.
When Your Python Codebase Starts Fighting You
You can feel it when structure breaks down.
- Adding a feature requires edits across random files.
- Imports form circles of pain: A imports B, B imports A.
- No one agrees where new modules belong.
A typical messy repo looks like this:
project/
├── api.py
├── db_utils.py
├── models.py
├── helpers.py
├── scripts/
│ ├── backfill_data.py
│ ├── run_server.py
├── tests/
│ ├── test_api.pyEverything works — until it doesn’t. New engineers fear refactors. Deploys slow down. And “just one more helper” becomes a symptom of structural collapse.
If every change feels risky and slow, your problem is probably structure, not just code quality.
Core Principles Behind Maintainable Project Structure
A maintainable structure is less about elegance and more about change management.
Key ideas
- Group by domain, not only by file type. Code that changes together should live together.
- One-way dependencies. Outer layers can depend on inner ones, but never the reverse.
- Stable interfaces. Modules used by many parts of the system should change slowly.
Think of your structure like a city:
- Downtown (core logic) rarely moves.
- Neighborhoods (services, adapters) grow and evolve.
- Entry points (CLI, API, jobs) connect the system to the outside world.
Structure should reflect how the system changes over time, not just how it was first built.
Designing a Clear Layout: Apps, Domains, and Shared Code
At scale, you need a layout that’s obvious to navigate, even for someone new.
A common pattern that works for both apps and data systems:
project/
├── src/
│ └── project_name/
│ ├── api/
│ ├── domain/
│ ├── services/
│ ├── shared/
│ └── __init__.py
├── tests/
│ ├── unit/
│ ├── integration/
│ └── __init__.py
├── scripts/
├── pyproject.toml
└── README.mdGuidelines
domain/: business rules, entities, and core functions.services/: orchestration, data access, or integration logic.api/orcli/: entrypoints connecting the system to users or other systems.shared/: common helpers and abstractions — used with care to avoid a new “utils” dumping ground.
Bad patterns:
helpers.py,misc.py, orcommon/full of unrelated code.- Mixing scripts with reusable modules.
Your directory tree is your first piece of documentation, so make it tell a clear story.
Dependency Boundaries, Interfaces, and Layered Design
Structure enforces discipline only if dependencies flow in one direction.
A good mental model:
entrypoints -> services -> domain -> sharedFor example:
# src/project_name/api/handlers.py
from project_name.services.order_service import create_order
def handle_create(request):
data = request.json()
return create_order(data)# src/project_name/services/order_service.py
from project_name.domain.order import Order
from project_name.shared.db import save
def create_order(data):
order = Order(**data)
save(order)Notice how the API handler knows nothing about the database — it just calls a service.
The service knows how to persist data, but not about HTTP or request parsing.
Every time you prevent a shortcut import, you protect future refactors.
Managing Config, Environments, and Secrets Safely
Messy projects often have configuration scattered across modules or hardcoded into logic.
Get Code With Ahmad’s stories in your inbox
Join Medium for free to get updates from this writer.
Bad:
API_KEY = "prod-key"
DB_PATH = "/var/lib/db.sqlite"Better:
# src/project_name/config.py
from pydantic import BaseSettings
class Settings(BaseSettings):
env: str = "dev"
db_url: str
api_key: str
settings = Settings()- Centralized config makes environment changes explicit.
- Keep config reading separate from usage.
- Default values belong in one place — not sprinkled across modules.
Good config structure makes it obvious what can change per environment and what must stay consistent.
Keeping Quality High: Tests, Tooling, and Automation
A healthy structure makes testing easy — not an afterthought.
Testing layout
Mirror your src/ structure:
tests/
├── unit/
│ └── test_domain_order.py
├── integration/
│ └── test_order_service.pyAutomation and tooling
- Add pre-commit hooks for formatting and linting.
- Keep lint and coverage config close to the project (e.g., in
pyproject.toml). - Add
scripts/ortools/with Make targets for common workflows liketest,lint, andserve.
Example Makefile snippet:
test:
pytest -q
lint:
black src/ tests/
mypy src/A maintainable project makes the right way the easiest way by baking quality into its structure.
Evolving the Structure Without Breaking Everything
Most teams don’t get to start from scratch. The challenge is evolution.
Gradual strategies
- Strangler pattern: create new packages (e.g.,
new_domain) and migrate code over time. - Deprecation paths: mark old modules with warnings and docstrings pointing to replacements.
- Shim layers: temporarily import legacy functions into new modules while rewriting consumers.
Example:
# legacy/orders.py
def calculate_total(...):
...
# new_domain/order.py
from legacy.orders import calculate_total # temporary shimDocument the migration plan in ARCHITECTURE.md or a simple README in each major directory.
The best structure is one your team can actually move toward, not an ideal diagram that never leaves a slide.
Quick Checklist for a Healthy Python Project
src/layout with one clear top-level package.- Domain, service, and entrypoint layers separated.
- Centralized configuration and environment handling.
- Tests that mirror source structure.
- No circular imports across domains.
- Automated formatting and linting built in.
Glossary
- Domain layer
The core business logic and rules of the system - Service layer
Coordinates application behavior and integrates multiple domain components - Adapter
Code that connects the application to external systems such as databases or APIs - Entrypoint
The API, CLI, or background job that starts or triggers the system - Src layout
A project structure that places the main package undersrc/to avoid import ambiguity and accidental shadowing
A solid project structure takes discipline upfront — but it pays back in every safe refactor, every new hire, and every deploy that doesn’t spiral into chaos.
So: what part of your Python project scares you the most to touch, and what small structure change could make it safer next week?
Written by Ahmad, sharing insights at @CodeWithAhmad








