Packaging a project with pyproject.toml
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
From a script to a package
A single script is easy to share: you send the file. Once you have several modules, dependencies and a command-line entry point, you need a package. A package can be installed with pip, versioned and reused in other projects. The modern way to describe one is a single file called pyproject.toml.
A project layout that works
invoicer/
pyproject.toml
README.md
src/
invoicer/
__init__.py
calc.py
cli.py
tests/
test_calc.py
Putting the code under src/ prevents a subtle problem: with a flat layout, your tests might import the folder in your working directory instead of the installed package, and everything seems fine until you ship a broken install. The src layout forces you to test what users get.
The pyproject.toml file
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "invoicer"
version = "0.1.0"
description = "Small invoice calculation tools"
readme = "README.md"
requires-python = ">=3.11"
license = { text = "MIT" }
authors = [{ name = "Your Name", email = "you@example.com" }]
dependencies = [
"requests>=2.31",
]
[project.optional-dependencies]
dev = ["pytest>=8", "mypy>=1.10"]
[project.scripts]
invoicer = "invoicer.cli:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.mypy]
strict = true
What each section does
[build-system] tells pip which tool builds your project. Setuptools is the long-standing choice. Hatchling, Flit and Poetry are alternatives, and the file format is the same standard for all of them. [project] holds the name, version and metadata. requires-python blocks installs on versions you do not support. dependencies lists what your package needs at run time, with version ranges.
[project.optional-dependencies] defines extras. Here, pip install -e ".[dev]" installs the development tools too. [project.scripts] creates a command: after installation, typing invoicer runs the function main in invoicer/cli.py. The [tool.*] tables hold settings for other tools, so you do not need many separate config files.
The code
# src/invoicer/calc.py
def with_tax(amount: float, rate: float = 0.17) -> float:
return round(amount * (1 + rate), 2)
# src/invoicer/cli.py
import argparse
from invoicer.calc import with_tax
def main() -> None:
parser = argparse.ArgumentParser(description="Add tax to an amount")
parser.add_argument("amount", type=float)
parser.add_argument("--rate", type=float, default=0.17)
args = parser.parse_args()
print(with_tax(args.amount, args.rate))
if __name__ == "__main__":
main()
The __init__.py file can be empty. It marks the folder as a package.
Install it for development
Create and activate a virtual environment first, then:
pip install -e ".[dev]"
invoicer 1000
The -e flag means editable. Python points at your source folder instead of copying it, so changes take effect immediately. The command prints 1170.0.
Building a distributable file
pip install build
python -m build
This creates a dist/ folder containing a source archive (.tar.gz) and a wheel (.whl). A wheel is a pre-built package that installs fast. You can send the wheel to a colleague, or upload it to PyPI with twine. Try the TestPyPI site first when you publish for the first time, since you cannot reuse a version number once it is published.
Versions and dependencies
Use ranges in the package, such as requests>=2.31. Packages are libraries, so a loose range lets others combine them with other tools. For applications that you deploy, pin exact versions in a separate lock or requirements file so every deployment is the same. Tools like pip-tools, uv or Poetry produce lock files.
Common mistakes
- Forgetting the packages configuration. With a src layout, setuptools needs to know where to look. Without the
findsection you may build an empty wheel. - Naming conflicts. Check that your package name is free on PyPI, and do not name modules like standard library ones.
- Using absolute imports wrongly. Inside the package, import with
from invoicer.calc import .... Running a module file directly can break relative imports, so usepython -m invoicer.cli. - Forgetting to bump the version before uploading a new release.
- Old advice. Many tutorials still show
setup.pyandsetup.cfg. They still work, but new projects should usepyproject.toml.
Try it yourself
Turn one of your own scripts into a package named after it. Create the src layout, write a pyproject.toml with one dependency and one command-line entry point, install it in editable mode in a fresh virtual environment, and run the command. Then build a wheel and install it into a second clean environment to check that it works outside your project folder.
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "invoicer"
version = "0.1.0"
description = "Small invoice calculation tools"
readme = "README.md"
requires-python = ">=3.11"
license = { text = "MIT" }
authors = [{ name = "Your Name", email = "you@example.com" }]
dependencies = [
"requests>=2.31",
]
[project.optional-dependencies]
dev = ["pytest>=8", "mypy>=1.10"]
[project.scripts]
invoicer = "invoicer.cli:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.mypy]
strict = true
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account