SkilVaultSign inStart free

Catalogue / python-layout-decisions

python-layout-decisions

Older skill: source not recordedSignedGuides the user through arranging Python code — choosing between a src directory and a flat top level, carving packages by technical layer or business domain, keeping nesting shallow, splitting oversized modules, declaring exports with __all__ in modules and package init files, preferring absolute i…
---
name: python-layout-decisions
description: >
  Guides the user through arranging Python code — choosing between a src
  directory and a flat top level, carving packages by technical layer or
  business domain, keeping nesting shallow, splitting oversized modules,
  declaring exports with __all__ in modules and package init files,
  preferring absolute imports, placing test files, and reworking an
  existing repository safely. Use when creating a Python project
  skeleton, auditing or untangling a current layout, deciding what a
  module or package should export, or choosing where tests live. Not for
  Python syntax questions, runtime debugging, build and packaging
  configuration such as pyproject settings, or projects in other
  languages.
license: MIT
---

Laying Out Python Codebases

Arrange a Python repository so a reader can find any piece of code by prediction, see at a glance which names they are invited to import, and trace dependencies in one direction. Treat every choice below as a decision to settle with the user, judging each answer by two measures: cohesion — the contents of a unit change together — and dependency direction — imports point one way.

Orient before anything moves

Put three questions to the user first:

  • Greenfield or rework? For an existing tree, agree on the target layout using the decisions below, then apply the reworking procedure near the end; do not move files while still deciding.
  • Library or application? Strangers consume a library, so its importable surface deserves the most care. An application is consumed by its own tests and entry points, so its dependency direction matters most.
  • Who changes the code, and where do their changes cluster? The answer picks the carving axis two sections down.

Where the package sits at the top level

| Option | Shape | What it buys | What it costs | | --- | --- | --- | --- | | src layout | importable package under src/ | the repository root stops being a place the package can be imported from, which makes it unlikely that a tool loads the working copy in place of the installed build | the package is not reachable from the root on its own — bring it in either by installing it (an editable install is the usual development route) or by putting src/ on the module search path | | flat layout | package directory at the repo root | nothing to configure; the checkout imports the moment you open it | commands run from the root commonly place the checkout ahead of any installed build on the search path, so a test run can quietly exercise source you believed you had replaced |

State precisely what the src layout does and does not guarantee. It stops the root from supplying the package, which makes accidental imports of the checkout unlikely rather than impossible: any setup that adds src/ itself to the module search path — a test runner's path option, an IDE run configuration, a search-path environment variable — imports the package straight from the working tree with no install at all, and that is a deliberate, supported way to develop. With neither an install nor a path entry in place, importing the package fails; installing is simply the more common route, not the only one. Recommend src for anything distributed, and accept flat for small internal work that will never sit beside an installed distribution sharing its name.

ledgerly/
├── src/
│   └── ledgerly/
│       ├── __init__.py
│       ├── invoices/
│       ├── payments/
│       └── support/
├── tests/
├── pyproject.toml
└── README.md

Which axis carves the packages

Layers group by technical role and suit smaller applications whose features share machinery:

grebe/
├── webfront/    # HTTP routes and middleware
├── dispatch/    # scheduling rules
├── stores/      # database and cache access
├── records/     # dataclasses shared across layers
└── settings/    # configuration loading

Rule: webfront imports from dispatch, dispatch from stores; records and settings are imported by everyone and import no feature code back.

Domains group by business area and suit systems whose areas change on independent schedules:

ledgerly/
├── invoices/
│   ├── issuer.py
│   ├── invoice_store.py
│   └── events.py
├── payments/
│   ├── gateway.py
│   └── reconciler.py
└── support/
    ├── db.py
    └── errors.py

Hybrids are legitimate. A domain large enough may grow technical subfolders (invoices/webfront/, invoices/stores/) beside a top-level support/ for cross-cutting machinery. Judge each boundary on its own: does everything inside change for the same reason, and do dependencies still point inward without cycles? Reject blends whose only justification is habit, and do not forbid mixing axes on principle.

How deep to nest

Default to shallow. Admit a subpackage when a group of modules forms a unit others consume through one entry point, changes together and apart from the rest, or isolates a swappable piece behind a shared interface. File counts decide nothing: payments/gateways/ holding only card_api.py and bank_transfer.py is a sound package because both implement one interface callers switch between, while eight files importing each other at random signal a missing boundary, not a need for another folder. Treat a chain of directories that adds navigation without adding a boundary as a smell in itself.

What other code may import

Settle the semantics first, because __all__ is widely misdescribed:

| Situation | Result | | --- | --- | | from invoice_store import * with __all__ defined | binds exactly the listed names | | the same wildcard with no __all__ | binds every top-level name lacking a leading underscore — including modules the file imported for its own use, a frequent accidental leak | | from invoice_store import _migrate_schema | succeeds anyway; __all__ never blocks an explicit import | | a name listed in __all__ that the module never defines | the wildcard import raises at import time | | an underscore-prefixed name listed anyway | the wildcard binds it; legal, but it contradicts the convention readers rely on |

A package init's __all__ governs from ledgerly.invoices import * by the same rules. So __all__ is a wildcard controller plus a declared statement of intent that documentation generators and linters read — it is not access control. Privacy stays a naming convention: signal it with a leading underscore, and never place anything sensitive in a module on the strength of its being unlisted.

With that settled, declare __all__ in every module others import and in every package init, lifting the most-used names so consumers write from ledgerly import InvoiceIssuer instead of rummaging through submodules:

# ledgerly/invoices/invoice_store.py
"""Persistence for issued invoices."""

class InvoiceStore: ...
class InvoiceQuery: ...
class StoreUnavailable(Exception): ...

def _migrate_schema(): ...  # internal; wildcards never bind it

__all__ = ["InvoiceStore", "InvoiceQuery", "StoreUnavailable"]
# ledgerly/invoices/__init__.py
"""Invoice issuing and persistence."""
from ledgerly.invoices.issuer import InvoiceIssuer
from ledgerly.invoices.invoice_store import InvoiceQuery, InvoiceStore, StoreUnavailable

__all__ = ["InvoiceIssuer", "InvoiceQuery", "InvoiceStore", "StoreUnavailable"]

A root init may also carry the version beside its own list: __version__ = "1.4.0".

Import statements and file names

Use absolute imports everywhere, including init files. The reason is mechanical: a relative import resolves against the importing file's *package context* — its position in the tree. Move the file and the same statement may resolve to a different module than intended, or fail; run the file as a script and that context is missing entirely, so every relative import in it errors reporting an unknown parent package. Absolute statements survive moves unchanged, and when their target moves they fail loudly, naming the missing path — a repair you can make mechanically. Prefer from ledgerly.invoices.issuer import InvoiceIssuer over statements that count dots.

Name files in spelled-out snake_case (payment_gateway.py, never pay_gw.py), and let a file's primary class dictate its name (Reconciler lives in reconciler.py).

When a module splits

Inspect a file for these signals:

  • It answers unrelated responsibilities — HTTP parsing and SQL in one place.
  • Its classes change for different reasons or on different schedules.
  • Its import block reaches into many unrelated areas.
  • It has grown past a few hundred lines (say 400) — a prompt to look, not a rule; a genuinely cohesive module may earn more.
# split into
invoice_issuer.py    # rules for assembling an invoice
invoice_store.py     # saving and loading invoices
invoice_events.py    # event dataclasses emitted while issuing

# rather than
invoice.py           # all of the above plus stray helpers

Give each split file a docstring stating its role so the directory reads like a table of contents.

Where tests live

| Placement | Shape | Reason to choose it | | --- | --- | --- | | colocated | test_invoice_store.py beside invoice_store.py | coverage gaps visible at a glance, minimal configuration — common in small teams | | mirrored | tests/invoices/test_invoice_store.py under a root tests/ | test code sits outside the importable package tree, keeping that tree clean and matching what maintainers of distributed projects expect |

Be exact about what mirroring does and does not do. It changes where test code sits relative to the import tree; it does not by itself decide what lands in a distribution. Whether a built artifact contains test files is settled by build configuration — which directories and modules the build collects — so a root tests/ tree can still be swept into an artifact, and colocated tests can still be left out, depending on how the build is set up. The placements can also coexist: mainstream test runners collect beside-the-code files and a root suite in the same run once imports resolve, and some mature projects deliberately keep fast unit tests next to the code and slow end-to-end suites at the root. Treat placement as a convention to name, not a technical constraint: declare one default per repository, write the choice down, and let any exception follow a stated rule — by test kind or speed — rather than each author's mood. The real cost of an unspecified policy is that a newcomer cannot predict where the next test goes, not collection breakage.

Reworking an existing repository

  1. Map the present state: list modules, their sizes, and each file's import lines; that sketch is enough to expose clusters and cycles.
  2. Draft the target tree using the decisions above, writing one sentence per boundary stating what it protects, and record the directory map in the README.
  3. Show the user the plan and get an explicit go-ahead. Restructuring moves files and rewrites import statements across the whole repository, so nothing moves before approval.
  4. Migrate one subtree at a time, repairing imports after each batch.
  5. Run the test suite between batches; if it cannot run, stop and report rather than pressing on.

Defaults at a glance

| Situation | Default | | --- | --- | | Library others install | src top level, mirrored tests as the written default, __all__ in every module and init | | Small internal application | flat top level acceptable, layer axis, colocated tests | | Areas changing on independent schedules | domain axis plus a support package | | Swappable implementations behind one interface | their own subpackage regardless of file count | | Module past a few hundred lines | inspect for split signals; never split on size alone | | Slow integration suite beside colocated units | fine when the split follows a written rule |

What this skill must not do

Preview shortened. The full SKILL.md is in the pack.