Python Best Practices

Chapter 1 · Practice 5 of 5

Use a src layout and keep tests outside the package

From Versions, environments and project setup

Why it matters

In a flat layout, the package folder sits at the repository root, so Python can import it from the current directory even when it is not installed. Tests then pass locally against files that would never be part of the installed package.

The pytest docs strongly recommend a src layout:

text
pyproject.toml
src/
  orders/
    __init__.py
    service.py
tests/
  test_service.py

Install the project in editable mode (pip install -e . or uv sync) and the tests import exactly what users would. It also stops a stray orders.py script at the root from shadowing your package.