Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 16 / Topic 2 of 6

Project layout and pyproject.toml

The src layout

A package meant to be installed (not just a script you run where it sits) is usually laid out like this:

rupee-split/
├── pyproject.toml
├── README.md
├── src/
│   └── rupee_split/
│       ├── __init__.py
│       └── cli.py
└── tests/
    └── test_cli.py

Why the extra src/ folder, instead of putting rupee_split/ straight in the project root? Because of sys.path (Part 7, section 6): when you run a script, Python puts that script's own folder first on sys.path. If rupee_split/ sat next to a test file at the project root, import rupee_split could quietly succeed by finding the folder on disk — even if the package was never actually installed. That hides real packaging mistakes until a user, who does not have that folder sitting around, hits an ImportError. With src/ in the way, nothing makes rupee_split importable except installing it (section 3) or deliberately pointing at src/ — so your tests prove the installed package works, not just the folder.

pyproject.toml, table by table

pyproject.toml is the single configuration file for a modern Python project (it replaced the older trio of setup.py, setup.cfg and requirements.txt for packaging). It is TOML (Tom's Obvious, Minimal Language): sections in [brackets], key = value lines, lists in [...].

[project]
name = "rupee-split"
version = "0.1.0"
description = "Split a restaurant bill between friends, down to the rupee."
requires-python = ">=3.10"
dependencies = []

[project.scripts]
rupee-split = "rupee_split.cli:main"

[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
Table What it is for
[project] the metadata every tool agrees on: name, version, requires-python, dependencies (the "install this too" list, same job as requirements.txt)
[project.optional-dependencies] named extra groups, e.g. dev = ["pytest", "ruff"], installed with pip install "name[dev]"
[project.scripts] entry points: command = "package.module:function" creates a real command you can type in a terminal, which calls function()
[build-system] which tool turns your source into an installable package (the build backend) and what it needs to run

A build backend is the program that actually assembles your files into an installable package (a wheel, see section 5). You rarely call it directly; pip, uv and build all call it for you, reading [build-system] to know which one to use. Common ones: setuptools (the classic, most compatible default), hatchling (modern, simpler config), and uv's own uv_build (section 4).

Verified, from a real run of tomllib (the standard-library TOML reader, since Python 3.11 — see section 6):

import tomllib

with open("pyproject.toml", "rb") as f:    # tomllib needs the file opened in BINARY mode
    data = tomllib.load(f)

print(data["project"]["name"])                        # rupee-split
print(data["project"]["dependencies"])                # []
print(data["project"]["scripts"])                     # {'rupee-split': 'rupee_split.cli:main'}
print(data["build-system"]["build-backend"])          # setuptools.build_meta

tomllib can only read TOML; there is no standard-library writer. To generate or edit a pyproject.toml from code you would need a third-party package (tomli_w, or tomlkit for edits that preserve comments) — for everyday use, just edit the file by hand.

Full, runnable program: examples/03_tomllib_read_pyproject.py (reads examples/sample_pyproject.toml, a realistic sample file, and also shows a broken TOML string raising tomllib.TOMLDecodeError).

The sample package

examples/sample_package/ is a complete, tiny src-layout project you can walk through right now — rupee-split, a bill-splitting CLI. No install, no network needed to try it:

$ cd examples/sample_package
$ PYTHONPATH=src python -m rupee_split.cli 900 --people 3 --tip 10
Friend 1: pay ₹330
Friend 2: pay ₹330
Friend 3: pay ₹330
Total collected: ₹990
$ PYTHONPATH=src python -m pytest tests -q
......                                                                   [100%]
6 passed in 0.05s   (varies)

PYTHONPATH=src is a temporary stand-in for "this package is installed": it tells Python to also look inside src/ for packages, the same way an install would make rupee_split importable. It is for trying the code out only — section 3 is the real, permanent way.

Read more: the official Python Packaging User Guide.

Exercise 2: Read a pyproject.toml with tomllib

Scenario: You are writing a tool that checks a project's packaging metadata before a release. What to do: Inside main(), parse the TOML text below with tomllib.loads() and print:

  1. name, version and requires-python from [project].
  2. dependencies (the whole list).
  3. optional-dependencies with .get(..., {}), so a project without that table still prints {} instead of crashing.
  4. The single entry in [project.scripts]: split its value on ":" and print which function, from which module, the command runs.
  5. The build backend from [build-system].

Starting data:

PYPROJECT_TEXT = """
[project]
name = "library-manager"
version = "2.1.0"
requires-python = ">=3.10"
dependencies = ["sqlite-utils>=3.0"]

[project.scripts]
library-manager = "library_manager.cli:main"

[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
"""

Sample output:

name: library-manager
version: 2.1.0
requires-python: >=3.10
dependencies: ['sqlite-utils>=3.0']
optional-dependencies (default empty dict): {}
command 'library-manager' runs main() from library_manager.cli
build backend: setuptools.build_meta

💡 Hint: tomllib.loads(text) parses TOML already in a string; tomllib.load(file) reads an open binary file instead. next(iter(d.items())) gets the one key/value pair out of a single-entry dict without naming the key.


Show the solution to Exercise 2
"""Exercise 2: Reading a pyproject.toml with tomllib.

Run:   python ex02.py   (macOS/Linux: python3 ex02.py)
"""

import tomllib

PYPROJECT_TEXT = """
[project]
name = "library-manager"
version = "2.1.0"
requires-python = ">=3.10"
dependencies = ["sqlite-utils>=3.0"]

[project.scripts]
library-manager = "library_manager.cli:main"

[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
"""


def main() -> None:
    data = tomllib.loads(PYPROJECT_TEXT)
    project = data["project"]

    print("name:", project["name"])
    print("version:", project["version"])
    print("requires-python:", project["requires-python"])
    print("dependencies:", project["dependencies"])

    extras = project.get("optional-dependencies", {})
    print("optional-dependencies (default empty dict):", extras)

    command, target = next(iter(project["scripts"].items()))
    module, func = target.split(":")
    print(f"command '{command}' runs {func}() from {module}")

    print("build backend:", data["build-system"]["build-backend"])


if __name__ == "__main__":
    main()

Search the guide