Tutorials / Python: Intermediate to Advanced / Packaging a project with pyproject.toml

Packaging a project with pyproject.toml

14 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. 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 find section 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 use python -m invoicer.cli.
  • Forgetting to bump the version before uploading a new release.
  • Old advice. Many tutorials still show setup.py and setup.cfg. They still work, but new projects should use pyproject.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.

python
[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