Sub topic 1
Laying out a library: why the src layout
A library's folder structure decides what your tests import, what ends up in your built package, and how easily other tools can understand the project. This chapter explains the src layout, compares it with the flat layout, and sets up the project skeleton that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you can:
- Write Python modules and packages, and know what
__init__.pydoes. - Create a virtual environment and install things with
pip. - Use a terminal and basic Git commands.
You do not need to know anything about pyproject.toml or building yet. The next chapter covers that file.
Three names for one project
A library has up to three names, and beginners often mix them up:
- The repository name is the folder or GitHub project, such as
greeter. - The distribution name is the name people type after
pip install. It is set in the project metadata. - The import name is the name of the top-level package you write after
import.
These can differ. The distribution Pillow is imported as PIL, and beautifulsoup4 is imported as bs4. This tutorial keeps all three as greeter to stay simple. Pick an import name that is a valid Python identifier, which means lowercase letters, digits and underscores. A hyphen in an import name is a syntax error.
The flat layout and its hidden trap
In a flat layout, the package sits at the repository root next to the config files:
greeter/(the package)tests/pyproject.toml
This looks tidy, and it works well enough for scripts. For a library it has a trap. When you run python -m pytest from the repository root, Python puts the current directory at the front of sys.path. Your tests then import greeter straight from the source folder. They never touch the package that pip would install.
That means the tests can pass while the published package is broken. Here are three ways this happens:
- A new module exists in your folder but is not included in the built package. The tests find it locally. Users get an
ImportError. - A data file is read from the working directory and is missing from the wheel.
- Code depends on a file at the repository root that is never shipped.
You find out about these only after users report them.
The src layout
The src layout moves the importable package one level down, into a folder called src/:
greeter/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│ └── greeter/
│ ├── __init__.py
│ ├── cli.py
│ └── py.typed
└── tests/
└── test_greet.pyNow the repository root contains no greeter folder. Running python -m pytest from the root cannot import the package from the working directory, because src/ is not on sys.path. The package must be installed first, and that is the same path a user's copy takes. If a file is missing from the install, the tests fail on your machine before any user sees the problem.
What each file is for
| Path | Purpose |
|---|---|
| `pyproject.toml` | Project configuration and metadata. The next chapter covers it. |
| `README.md` | The long description shown on the PyPI project page. |
| `LICENSE` | The license text, which is shipped inside the built files. |
| `src/greeter/__init__.py` | Marks the package and defines its public names. |
| `src/greeter/cli.py` | Command-line code, kept apart from the library API. |
| `src/greeter/py.typed` | An empty marker that tells type checkers the package ships type hints. |
| `tests/` | Tests, kept outside the package so they are not shipped to users. |
Putting tests/ beside src/ rather than inside the package keeps the installed package small. It also stops users from getting a second copy of your tests in site-packages.
The package code
Here is the minimal library used throughout this tutorial:
# src/greeter/__init__.py
from importlib.metadata import version
__version__ = version("greeter")
def greet(name: str) -> str:
return f"Hello, {name}!"The __version__ line reads the version from the installed metadata. The version number then lives in one place only, which is pyproject.toml. This also shows the src layout at work. version("greeter") asks for the metadata of an installed distribution. If the package is not installed, it raises PackageNotFoundError. A flat layout would hide that mistake. The src layout fails on the first test run, so the problem shows up early.
A first test:
# tests/test_greet.py
from greeter import greet
def test_greet_names_the_person():
assert greet("Ada") == "Hello, Ada!"Working with the layout day to day
Because the package must be installed, you need a way to install it without rebuilding after every edit. An editable install does this. It links the installed package back to your source files, so edits take effect at once.
python -m venv .venv
source .venv/bin/activate
python -m pip install -e . pytest
python -m pytestOn Windows, activate with .venv\Scripts\activate instead. Once the package is installed in editable mode, import greeter works from any folder, and the tests run against the installed project. This setup assumes a pyproject.toml exists. The next chapters write it step by step.
Why tools like the src layout
The src layout also helps the build step:
- Automatic discovery. Setuptools looks for packages in
src/automatically. In a flat layout, folders such astests/,docs/andscripts/sit at the root too. Setuptools can then refuse to guess which folders are packages, or it can include the wrong ones. - Clear boundaries. Everything under
src/is code you intend to ship. Everything outside it is project tooling. - No accidental imports. A stray
greeter.pyor an oldbuild/folder in the root cannot shadow the real package.
Trade-offs and common mistakes
The src layout costs you something: you must install the project before you can import it, even for a quick check in a REPL. An editable install removes most of that friction. Some small projects, such as single-module scripts, do not need the extra folder.
Common mistakes with this layout:
- Adding
srctoPYTHONPATHorsys.pathto make tests pass. This recreates the flat-layout trap, because tests then import the source folder instead of the installed package. - Forgetting
__init__.py. Without it,greeteris a namespace package. Some tools may then not include it as expected. Add the file. - Putting
tests/insidesrc/greeter/. The tests then ship to every user. - Naming the package after a standard-library module, such as
src/email/. This causes confusing import conflicts. - Leaving out
py.typed. The package works without it, but type checkers treat it as untyped. A later chapter covers this file.
Exercise
Your tests pass locally in a flat layout, but a user reports ModuleNotFoundError for greeter.utils after installing from PyPI. Explain how this can happen, and how the src layout would have caught it.
Show answer
In a flat layout, running pytest from the repository root puts the working directory on sys.path, so the tests import greeter/utils.py straight from the source folder. If the build did not include that module in the package, the published install lacks it, but the tests never notice. In a src layout, the root has no greeter folder, so the tests can only import the installed copy. The missing module would make the tests fail before release.
Exercise
A teammate fixes a failing test in a src layout by adding src to PYTHONPATH. Why is this a poor fix, and what should they do instead?
Show answer
It lets Python import from the source folder directly, so the tests no longer check the installed package. This brings back the problem the src layout avoids. They should install the project with python -m pip install -e . and run python -m pytest, so the tests import the installed package.