Skip to content

Lesson 3 of 9 · 20m

Build Backends and the src Layout

How setuptools, hatchling, flit, and poetry-core differ — and how the src layout prevents the oldest packaging bug in Python.

A build backend is the code that turns your source tree into an sdist and wheel. PEP 517 made the backend pluggable, which means the correct question is no longer "how do I configure setup.py?" but "which backend's model matches this project?"

PEP 517 in one picture

pyproject.toml
  [build-system]
  requires = [...]
  build-backend = "..."
        |
        v
python -m build / pip / uv build
        |
        +--> sdist (.tar.gz)
        +--> wheel (.whl)

python -m build invokes the backend in an isolated environment. That isolation is important: your laptop's installed packages are not supposed to leak into the artifact. If a build only works with --no-isolation, treat that as a bug in the declared build requirements.

Choose a boring backend

  • hatchling: modern, explicit, strong defaults, good for libraries and applications.
  • setuptools: ubiquitous and maximally compatible, but configuration has decades of accumulated corners.
  • flit-core: small and clean for simple pure-Python libraries.
  • poetry-core: the build backend used by Poetry-managed projects.

For most new libraries, hatchling or setuptools is the pragmatic choice. The backend is infrastructure, not a brand. Pick one the team understands and use it consistently.

Use the src layout unless you have a reason not to

acme-metrics/
  pyproject.toml
  README.md
  src/
    acme_metrics/
      __init__.py
      client.py
  tests/
    test_client.py

The src layout prevents the classic false positive: running tests against the source directory instead of the installed artifact. With a flat layout, Python can import acme_metrics because the project root happens to be on sys.path. With src, tests exercise what packaging actually produced.

Configure the backend explicitly:

[tool.hatch.build.targets.wheel]
packages = ["src/acme_metrics"]

Don't import the package during the build

A common setuptools-era failure is importing the package in setup.py just to read __version__. That means dependencies must be installed before the package can even build, and partially installed environments explode. Use static metadata or a backend-supported version source instead.

Field notes

  • Delete dead setup.py, setup.cfg, and MANIFEST.in files when migrating; overlapping configuration is worse than verbose configuration.
  • pip wheel . --no-deps is a quick smoke test that the backend can produce a wheel.
  • If tests pass only from the project root, you may be testing accidental path behavior rather than the package.

Was this lesson helpful?

Sign in to rate