What You’ll Learn
In this lesson, you will learn how to turn a Python utility into an installable project with pyproject.toml. You will define project metadata, declare dependencies, configure package discovery, build the project, and install it locally in a virtual environment.
- Understand the role of
pyproject.toml. - Configure a project using the standard
srclayout. - Declare dependencies and a command-line entry point.
- Build and locally install a Python package.
- Recognize common packaging mistakes.
The Concept
A Python project can run correctly from its source directory without being packaged. However, other people and tools need a consistent way to install it, discover its modules, learn which dependencies it needs, and run its command-line tools.
pyproject.toml is the modern configuration file for Python projects. It can contain:
- Build-system information, such as which backend creates the package.
- Project metadata, such as the name, version, and supported Python versions.
- Runtime dependencies that installers should install automatically.
- Configuration for finding packages inside the project.
- Command-line scripts that should be created during installation.
This lesson uses setuptools as the build backend. The backend performs the actual build, while tools such as pip use the information in pyproject.toml to invoke it.
The src layout keeps importable code inside a dedicated directory. This helps reveal accidental imports from the project root during development, because the package must be installed before it can be imported normally.
Basic Example
Imagine a utility called report-tools. It accepts a status on the command line and prints a formatted message using the third-party rich package.
Create this project structure:
report-tools/
├── pyproject.toml
└── src/
└── report_tools/
├── __init__.py
└── cli.pyPlace the following configuration in pyproject.toml:
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "report-tools"
version = "0.1.0"
description = "A command-line utility for displaying report statuses"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
"rich>=13.7"
]
[project.scripts]
report-status = "report_tools.cli:main"
[tool.setuptools.packages.find]
where = ["src"]The readme field refers to a file that should exist in the project root. Create a small README file so the build metadata is complete:
# Report Tools
A command-line utility for displaying report statuses.Create an empty __init__.py file in src/report_tools, then add the command-line implementation to cli.py:
import argparse
from rich.console import Console
console = Console()
def main():
parser = argparse.ArgumentParser(
description="Display the status of a report."
)
parser.add_argument(
"status",
choices=["ready", "running", "failed"],
help="The current report status.",
)
args = parser.parse_args()
messages = {
"ready": "The report is ready to review.",
"running": "The report is still being generated.",
"failed": "The report generation failed.",
}
console.print(messages[args.status])
if __name__ == "__main__":
main()From the project root, create and activate a virtual environment, then install the project in editable mode:
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e .On Windows PowerShell, activation uses a different command:
.venv\Scripts\Activate.ps1After installation, run the command declared under [project.scripts]:
report-status readyExpected Output
The report is ready to review.How the Code Works
The [build-system] table tells packaging tools how to build the project:
requireslists packages needed during the build. It is separate from the dependencies needed when the application runs.build-backendselects setuptools as the component that creates the package.
The [project] table contains metadata that installers and package indexes can use. The dependencies list is especially important: installing this project causes rich to be installed automatically. This is preferable to telling every user to install dependencies manually. For another practical example of installing the tqdm package, consider how a third-party library becomes part of a project’s declared requirements.
The [project.scripts] table creates an executable command when the package is installed. The value report_tools.cli:main means:
- Import the
report_tools.climodule. - Call its
mainfunction when someone runsreport-status.
The [tool.setuptools.packages.find] table tells setuptools to search for packages under src. The directory name report_tools uses an underscore because Python import names cannot contain a hyphen, while the distribution name report-tools can use one.
The command python -m pip install -e . performs an editable installation. The project is installed into the environment, but changes to the source files are immediately available without rebuilding after every edit. For a final artifact, use a regular installation from a built wheel instead.
Another Example
A different utility might collect the title from a web page. This project has two runtime dependencies, so it demonstrates why a package configuration is more maintainable than a list of manual installation commands.
Projects that combine HTTP requests with HTML parsing, such as Python projects using Requests and Beautiful Soup, are a useful real-world case for declaring multiple dependencies together.
Here is the project configuration:
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "page-title-checker"
version = "0.1.0"
description = "Fetch and display a web page title"
requires-python = ">=3.9"
dependencies = [
"requests>=2.31",
"beautifulsoup4>=4.12"
]
[project.scripts]
page-title = "page_title_checker.cli:main"
[tool.setuptools.packages.find]
where = ["src"]With an empty src/page_title_checker/__init__.py, place this code in src/page_title_checker/cli.py:
import argparse
import requests
from bs4 import BeautifulSoup
def main():
parser = argparse.ArgumentParser(
description="Display the title of a web page."
)
parser.add_argument("url", help="The URL to inspect.")
args = parser.parse_args()
response = requests.get(args.url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
title = soup.title.get_text(strip=True) if soup.title else "(untitled page)"
print(title)
if __name__ == "__main__":
main()After running python -m pip install -e . from this project’s root directory, the declared command can be used like this:
page-title https://example.comThis example also illustrates a useful dependency boundary. requests and beautifulsoup4 are runtime dependencies because the installed command imports them when it runs. They do not belong only in the build-system requirements.
Common Mistakes
- Using the wrong package name in the script entry point:
page_title_checker.cli:mainmust match the actual importable package and function name. The distribution name can contain hyphens, but the Python package name cannot. - Forgetting
__init__.py: Include this file in the package directory when using this straightforward setuptools layout. - Putting runtime dependencies under
[build-system]: Build requirements are used to create the package. Runtime dependencies belong in[project].dependencies. - Changing
pyproject.tomlbut testing an old installation: Reinstall the project, especially after changing dependencies or entry points. Editable mode makes source edits convenient, but metadata changes still need an installation update. - Building from the wrong directory: Commands such as
python -m pip install -e .expect the current directory to containpyproject.toml.
Try It Yourself
Create a package named inventory-checker using the src layout. Add a command named inventory-status that accepts one positional argument with the choices in-stock, low-stock, and out-of-stock. It should print a useful message for each choice.
Use project metadata with version 0.1.0, require Python 3.9 or newer, and install the project in editable mode. You can implement the messages with a dictionary, as in the first example.
Challenge
Build a package called sales-summary with the following requirements:
- Use the
src/sales_summarypackage layout. - Declare the
richdependency inpyproject.toml. - Create a
sales-summarycommand with a--regionoption. - Accept only
north,south, orwestas region values. - Print the number of completed orders for the selected region.
- Expose the command through
[project.scripts].
After installing the project, test it with sales-summary --region north.
Solution
Use this pyproject.toml in the project root:
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "sales-summary"
version = "0.1.0"
description = "Display completed order totals by region"
requires-python = ">=3.9"
dependencies = [
"rich>=13.7"
]
[project.scripts]
sales-summary = "sales_summary.cli:main"
[tool.setuptools.packages.find]
where = ["src"]Place this code in src/sales_summary/cli.py and create an empty src/sales_summary/__init__.py file:
import argparse
from rich.console import Console
console = Console()
COMPLETED_ORDERS = {
"north": 148,
"south": 96,
"west": 121,
}
def main():
parser = argparse.ArgumentParser(
description="Display completed orders for a sales region."
)
parser.add_argument(
"--region",
required=True,
choices=sorted(COMPLETED_ORDERS),
help="The sales region to report.",
)
args = parser.parse_args()
order_count = COMPLETED_ORDERS[args.region]
console.print(
f"Completed orders in {args.region}: {order_count}"
)
if __name__ == "__main__":
main()Install and run the challenge solution with:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e .
sales-summary --region northThe command works because the entry point maps sales-summary to sales_summary.cli:main. The dependency is installed from the project metadata, package discovery searches under src, and argparse rejects regions that are not present in the dictionary.
Key Takeaways
pyproject.tomlcentralizes build settings, metadata, dependencies, and command-line entry points.- Runtime packages belong in
[project].dependencies, while build tools belong in[build-system].requires. - The
srclayout works with setuptools package discovery configured withwhere = ["src"]. - A
[project.scripts]entry creates a command that calls a Python function after installation. - Use editable installation during development and build a regular package when preparing an artifact for distribution.



