Sub topic 2
pyproject.toml: one file that describes the project
This chapter assumes you can write and import Python packages, use a virtual environment and pip, and read basic TOML. By the end you should know what each part of pyproject.toml is for and who reads it. You should also be able to recognize the errors people hit most often.
Why one file
Older Python projects spread their configuration across several files:
setup.pyran arbitrary code to describe the package.setup.cfgheld declarative metadata for setuptools.requirements.txtlisted dependencies.MANIFEST.incontrolled which extra files went into the source archive.
Tools had to run setup.py just to learn the project's name or dependencies. That made installs fragile, because you could not know what a project needed in order to build until you had already run its code.
pyproject.toml replaced this with one static, declarative file. Three standards define it:
- PEP 518 introduced the
[build-system]table. - PEP 517 defined how a frontend talks to a backend.
- PEP 621 defined the
[project]table.
Because the file is plain TOML, any tool can read it without running your code.
The three kinds of table
A pyproject.toml has three kinds of top-level table, each with a different reader.
| Table | Read by | Purpose |
|---|---|---|
| `[build-system]` | Build frontends such as `pip` and `build` | Names the backend and what to install before building |
| `[project]` | Backends, PyPI, installers | Metadata: name, version, dependencies, scripts |
| `[tool.*]` | The named tool only | Private configuration for pytest, ruff, mypy, setuptools, and so on |
The rest of this chapter walks through each table using the greeter library from the tutorial.
A complete example
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "greeter"
version = "0.1.0"
description = "A tiny library that builds greeting messages."
readme = "README.md"
requires-python = ">=3.9"
license = "MIT"
license-files = ["LICENSE"]
classifiers = [
"Programming Language :: Python :: 3",
]
dependencies = []
[project.optional-dependencies]
test = ["pytest"]
[project.scripts]
greeter = "greeter.cli:main"The [build-system] table
This table has two keys:
requireslists the packages that must be installed in a temporary, isolated environment before the build starts.build-backendis the dotted path to the object that implements the build. For setuptools it issetuptools.build_meta.
The setuptools>=77 floor matters here. Setuptools 77 is the first version that understands the SPDX-style license = "MIT" string and license-files. With an older setuptools, the build fails because it expects a table in that field.
If you leave out [build-system] entirely, pip assumes legacy setuptools behavior. The result is a package that builds on one machine and not on another, depending on which setuptools is installed. Always declare the table.
The next chapter covers how the frontend uses these keys. For now, remember that these two lines are the only part of the file the frontend reads before it hands control to the backend.
The [project] table
The [project] table holds the metadata that ends up in the package's METADATA file, which PyPI and pip read. The fields in the example do the following:
nameis the distribution name. This is what users type afterpip install, and it need not match the import name, though it usually does. PyPI treats-,_, and.as equivalent and ignores case, soMy_Libandmy-libare the same project.versionis a PEP 440 version string, covered in a later chapter.descriptionis a one-line summary that PyPI shows in search results.readmepoints to a file whose contents become the long description on the project page. A.mdextension tells PyPI to render it as Markdown.requires-pythonmakes pip refuse to install the package on unsupported interpreters, and it also makes pip pick an older compatible release when one exists.licenseandlicense-filesdeclare the license as an SPDX expression and name the files to include in the archives.classifiersare standardized tags from a fixed list that PyPI uses for filtering. A misspelled classifier is rejected at upload time.dependencieslists runtime requirements, using the same specifier syntax as pip.
Optional dependency groups go under [project.optional-dependencies]. Users install them with pip install "greeter[test]". Console commands go under [project.scripts]. Each line maps a command name to module:function, so greeter = "greeter.cli:main" creates a greeter command that calls main() from greeter/cli.py.
Static and dynamic fields
By default every field in [project] is static, meaning you write its value in the file. If you want a backend to compute a field, such as the version from a Git tag, you must list it explicitly:
[project]
name = "greeter"
dynamic = ["version"]A field that is not in dynamic cannot be supplied by the backend. If you put version in both places, the build fails. This tutorial keeps the version static, and the package reads it back through importlib.metadata, so the number lives in one place.
The [tool] tables
Anything under [tool.<name>] belongs to that tool. Standards say only that other tools must ignore tables they do not own. Examples:
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.setuptools.package-data]
greeter = ["py.typed"]The [tool.setuptools] tables control backend-specific behavior, such as extra data files. Switching to another backend, like hatchling or flit-core, means replacing [build-system] and any [tool.setuptools.*] tables. The [project] table stays the same, which is the main benefit of standardizing it.
Checking the file
A quick way to catch syntax errors is to parse the file with the standard library. tomllib exists in Python 3.11 and later. On older versions, install tomli and import it instead.
import tomllib
from pathlib import Path
data = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))
print(sorted(data))
print(data["build-system"]["build-backend"])
print(data["project"]["name"])For the example above, this prints the three table names, then setuptools.build_meta, then greeter. Parsing only proves the TOML is valid. It does not prove the metadata is correct. A real build, covered later, does that.
Common errors
- Unquoted strings. TOML requires quotes around strings.
name = greeteris a syntax error. - Redefined tables. Writing
[project]twice is invalid. Put all keys in one place. - Wrong table for a key.
dependenciesbelongs under[project], not[build-system]. Build-time needs go inrequires, and runtime needs go independencies. - Setuptools too old. An error about
project.licenseusually means the build environment has a setuptools older than 77. Raise the floor inrequires. - Dynamic conflicts. A field is both set statically and listed in
dynamic, or it is computed by the backend but missing fromdynamic. - Missing readme.
readme = "README.md"fails if the file is absent or misnamed. Paths are relative to the directory containingpyproject.toml.
Exercise
A teammate adds pytest to requires under [build-system] so that "tests can run". What goes wrong, and where should pytest go instead?
Show answer
requires lists only what is needed to build the package, so pytest would be installed in every build environment for no reason, and users who install the package would not get it. Test tools belong in an optional dependency group, for example test = ["pytest"] under [project.optional-dependencies], installed with pip install ".[test]".
Exercise
Why does pyproject.toml list dynamic = ["version"] when the version is computed by the backend, instead of just leaving version out?
Show answer
A backend may only supply fields that the project declares as dynamic. Listing the field tells every tool that the value is not in the file and must be obtained from the backend. Without that declaration, the build fails because a required static field is missing.