Laying Out a Python Package: A Five-Chapter Web Read

Python gives you several ways to arrange a project on disk, and most of them work until the day they do not. This chaptered guide explains the src layout recommended by the Python Packaging User Guide, why it catches a whole class of mistakes, and how the rest of the project fits around it.

Chapter 1: Flat versus src

In a flat layout the importable package sits at the repository root next to pyproject.toml. In a src layout it sits one level down, inside a src/ directory.

example-lib/
  pyproject.toml
  README.md
  src/
    example_lib/
      __init__.py
      core.py
      py.typed
  tests/
    test_core.py

The difference matters when you run tests. With a flat layout, Python can import the package straight from the working directory, so tests pass even when the installed distribution is missing a file. With src, the package is only importable once installed, which forces the tests to exercise what users will actually get.

Chapter 2: The pyproject.toml that goes with it

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "example-lib"
version = "0.3.0"
requires-python = ">=3.9"
dependencies = ["attrs>=22"]

[project.scripts]
example-cli = "example_lib.cli:main"

Note that the distribution name uses a hyphen while the import name uses an underscore. That is common and allowed, but document it in the README so nobody tries import example-lib. Most modern backends, including Hatchling and setuptools, detect a src layout automatically; check your backend's documentation if they do not.

Chapter 3: Data files and type markers

Non-Python files such as templates or JSON schemas must be inside the package directory and included by the build backend. Load them with importlib.resources, not by building paths from __file__, so they work from zipped or unusual installs. If you ship type hints, add an empty py.typed file to the package directory, as described in PEP 561; without it, type checkers ignore your annotations.

Chapter 4: Testing the installed copy

  1. Install in editable mode for daily work: pip install -e .
  2. In CI, build the wheel and install that instead, then run the test suite against it.
  3. Use a tool such as nox or tox to repeat this across supported Python versions.

The src layout makes step 2 meaningful, because there is no stray copy of the package on the path to hide a packaging bug.

Chapter 5: When flat is fine

A single-module script published for convenience, or a project whose tests always run against a built wheel anyway, can live happily with a flat layout. The point of src is protection by default, not doctrine. If you switch an existing project, expect to update import paths in configuration files, coverage settings and documentation builds, and do it in one focused pull request.

See also the Python packaging course outline and PyPI Trusted Publishing setup.