Skip to content

Lesson 45 of 52Real projects

Project Structure

Lay out a real Python project with a src layout, pyproject.toml, tests, config, entry points and quality tools.

16 min read0/4 questions

The first thing a reviewer or hiring manager sees in your repo is its shape. A clean layout with pyproject.toml, a tests/ folder, a linter and a lock file says "this person has shipped software". A pile of loose scripts says the opposite. The good news: the modern layout is a convention, so learn it once and reuse it everywhere.

Flat layout vs src layout

There are two common shapes. In the flat layout your package folder sits at the root. In the src layout it lives one level down, inside src/.

todo-cli/
  pyproject.toml
  src/
    todo/
      __init__.py
      cli.py
  tests/
    test_cli.py

Why bother with src/? In the flat layout, running tests from the project root lets Python import todo straight from the folder, even if your packaging is broken. Your tests pass locally and the installed package fails for users. With the src layout, the package is only importable once it is properly installed into the venv (which uv sync does for you in editable mode), so tests exercise what users actually get. Tools like uv init --package create a src layout by default.

Quick check
What is the main benefit of the src layout?
Need a nudge? A hint rules out a wrong answer.

A small CLI app

todo-cli: a command-line app
  • todo-cli/
  • .gitignore.venv/, __pycache__/, .env
  • .python-version3.13 (read by uv)
  • pyproject.tomlmetadata, deps, tools, entry point
  • uv.lockexact versions, committed
  • README.md
  • src/
  • todo/
  • __init__.py__version__ = "0.1.0"
  • __main__.pylets you run python -m todo
  • cli.pyargument parsing, main()
  • store.pyload and save tasks (JSON file)
  • models.pyTask dataclass
  • tests/
  • conftest.pyshared pytest fixtures
  • test_store.py
  • test_cli.py

Notice the split. cli.py only deals with the command line. store.py only deals with persistence. models.py only holds data. Each piece can be tested on its own, and the business logic never reads sys.argv directly.

pyproject.toml, line by line

pyproject.toml is the one config file for a modern Python project. It is written in TOML, a simple key = value format with [sections]. It replaced setup.py, setup.cfg, and most tool-specific config files.

pyproject.toml
[project]
name = "todo-cli"                 # the distribution name on PyPI
version = "0.1.0"
description = "A tiny todo list for the terminal"
readme = "README.md"
requires-python = ">=3.13"        # refuse to install on older Pythons
dependencies = [                  # direct runtime dependencies only
    "rich>=13.9",
]
 
[project.scripts]
todo = "todo.cli:main"            # installs a `todo` command that calls main()
 
[dependency-groups]
dev = ["pytest>=8.3", "ruff>=0.9", "mypy>=1.14", "pytest-cov>=6.0"]
 
[build-system]                    # how to build the package
requires = ["hatchling"]
build-backend = "hatchling.build"
 
[tool.ruff]                       # each tool reads its own [tool.x] section
line-length = 100
 
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]   # pycodestyle, pyflakes, isort, bugbear, pyupgrade
 
[tool.mypy]
strict = true
 
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
  • [project] is standard metadata that every tool understands: name, version, supported Python, dependencies.
  • [project.scripts] defines entry points: todo = "todo.cli:main" means "when installed, create a todo command that imports todo.cli and calls main()".
  • [dependency-groups] holds dev-only tools that are not shipped to users (uv add --dev writes here).
  • [build-system] names the backend (hatchling, setuptools, uv_build) that turns your code into an installable package.
  • [tool.*] sections configure individual tools.

Python 3.11+ can read TOML itself with tomllib, which is how tools load this file:

Python
import tomllib text = '''[project]name = "todo-cli"version = "0.1.0"dependencies = ["rich>=13.9"] [project.scripts]todo = "todo.cli:main"''' config = tomllib.loads(text)print(config["project"]["name"], config["project"]["version"])print(config["project"]["dependencies"])module, func = config["project"]["scripts"]["todo"].split(":")print(f"`todo` runs {func}() from {module}")
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/5 matched

Match each pyproject.toml section to its job.

Choose an item, then its match on the other side.

Entry points: main() and __main__.py

Keep the entry point thin. Parse arguments, call into your real code, return an exit code. Accepting argv as a parameter makes it trivial to test.

Python
import argparse def main(argv=None): parser = argparse.ArgumentParser(prog="todo") sub = parser.add_subparsers(dest="command", required=True) add = sub.add_parser("add") add.add_argument("title") add.add_argument("--priority", type=int, default=1) sub.add_parser("list") args = parser.parse_args(argv) if args.command == "add": print(f"added {args.title!r} (priority {args.priority})") else: print("listing tasks") return 0 main(["add", "write tests", "--priority", "2"]) # what `todo add ...` would runmain(["list"])
Output
Press Run (⌘ Enter) to see what happens.

A src/todo/__main__.py containing from todo.cli import main; raise SystemExit(main()) lets you also run the app with python -m todo.

Configuration and .env

Settings that change between environments (database URLs, API keys, debug flags) do not belong in code. The convention, from the "twelve-factor app" guidelines, is to read them from environment variables. During development you keep them in a .env file that is loaded at startup and never committed. Commit a .env.example with dummy values instead, so teammates know what to set.

.env
DATABASE_URL=postgresql://localhost/todo
DEBUG=true
API_KEY=dev-only-not-a-real-key
Python
import os os.environ.setdefault("DEBUG", "true") # pretend the shell set this DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///todo.db")DEBUG = os.environ.get("DEBUG", "false").lower() in {"1", "true", "yes"} print(DATABASE_URL)print("debug mode:", DEBUG)
Output
Press Run (⌘ Enter) to see what happens.

Environment variables are always strings, so convert them deliberately. In FastAPI projects, pydantic-settings does this loading, conversion and validation for you.

Quick check
Which of these belongs in git?
Need a nudge? A hint rules out a wrong answer.

A web API layout (preview)

A FastAPI service uses the same ideas, with the code split by layer: HTTP routes on top, business logic in services, data access below. You will build exactly this in the Python Backend course.

shop-api: a FastAPI service
  • shop-api/
  • pyproject.toml
  • uv.lock
  • .env.example
  • Dockerfile
  • src/
  • shop/
  • __init__.py
  • main.pyapp = FastAPI(); include routers
  • config.pySettings loaded from env vars
  • api/
  • __init__.py
  • routes/
  • products.py@router.get("/products")
  • orders.py
  • schemas/Pydantic request/response models
  • product.py
  • services/business logic, no HTTP here
  • pricing.py
  • db/
  • session.pyengine and session
  • models.pySQLAlchemy tables
  • tests/
  • conftest.pytest client, test database
  • api/
  • test_products.py
  • services/
  • test_pricing.py

Tests mirror the source tree, so finding the test for services/pricing.py is obvious: tests/services/test_pricing.py.

Quality tools: Ruff, mypy, pre-commit

Three tools give you most of the value:

ToolWhat it doesCommand
RuffLinter and formatter in one (replaces flake8, isort, black). Extremely fast.uv run ruff check --fix . and uv run ruff format .
mypy (or pyright)Static type checking from your hintsuv run mypy src
pytestRuns your testsuv run pytest
pre-commitRuns checks automatically on every git commitpre-commit install once
.pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.12.0   # pin to the latest release
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

Run the same commands in CI (GitHub Actions), so nothing reaches main without passing lint, types and tests.

Put it in order4 steps

Order a typical CI job for a Python project.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

Parse a .env file

Write parse_env(text) that turns the contents of a .env file into a dict of strings, like the loaders in python-dotenv and pydantic-settings do.

Rules:

  • Skip blank lines and lines whose first non-space character is #.
  • A line may start with export (shell style); ignore that prefix.
  • Split on the first =. Strip spaces around the key and the value. Skip lines with no =.
  • If the value is wrapped in matching quotes ("..." or '...'), remove them and keep everything inside exactly, including #.
  • Otherwise, # (a space then #) starts an inline comment: cut it off and strip again.
  • If a key appears twice, the later value wins.
text = """
# database
DATABASE_URL=postgresql://localhost/app
export DEBUG = true   # local only
GREETING="hello # not a comment"
EMPTY=
"""
parse_env(text)
# {"DATABASE_URL": "postgresql://localhost/app", "DEBUG": "true",
#  "GREETING": "hello # not a comment", "EMPTY": ""}
Python
def parse_env(text: str) -> dict[str, str]: # Handle one line at a time. pass
Key terms
src layout
Putting the package in src/<name>/ so tests import the installed package, not the raw folder.
pyproject.toml
The standard project config file: metadata, dependencies, entry points, build backend and tool settings.
entry point
A [project.scripts] mapping like todo = "todo.cli:main" that installs a command.
.env
A local, uncommitted file of environment variables for development settings and secrets.
Ruff
A very fast Python linter and formatter configured in [tool.ruff].
pre-commit
A tool that runs linters and formatters automatically before each commit.