Programming languages · Intermediate · 20 min
Package a Python project with uv and pyproject.toml
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15.2 · uv 0.13.10
You will turn a small currency-formatting module into an installable Python package with a src layout, a command-line entry point, an optional extra and a dev dependency group, then lock it, build a wheel and an sdist, and prove the wheel works in a clean environment.
On this page
A uv project that you only run with uv run is an application living in one folder. A package is something else: a file other people (or your own servers) can install with pip or uv, which brings its own dependencies, puts its code on the import path and can add a command to the shell. Python packages ship in two forms. A wheel (.whl) is a ready-to-install zip. An sdist (.tar.gz) is the source, which an installer can build into a wheel.
In this tutorial you package money-labels, a small library that turns 1234.5 and NGN into ₦1,234.50. It has no required dependencies, an optional extra that pulls in Babel for locale-aware formatting, a money-label command, and pytest and Ruff as development tools that are never shipped to users. It picks up where the virtual environments tutorial stops.
Step 1 · Create a packaged project with a src layout
Make a demo folder and ask uv for a packaged project. --package adds a build system and puts the code under src/:
mkdir -p ~/packaging-demo
cd ~/packaging-demo
uv init --package --python 3.15 money-labels
cd money-labels
find . -path ./.git -prune -o -type f -print | sortuv creates pyproject.toml, README.md, .python-version, .gitignore and src/money_labels/__init__.py, and runs git init if Git is installed. Notice the two spellings. money-labels is the distribution name, the one people install. money_labels is the import name, because a hyphen is not allowed in a Python identifier.
The src/ folder matters. With the code one level down, Python run from the project folder cannot import money_labels by accident from the working directory. Your tests import the installed package, so a file you forgot to include in the package shows up as a failure on your machine, not on a user's.
Check it worked
The find output lists ./.python-version, ./README.md, ./pyproject.toml and ./src/money_labels/__init__.py (plus ./.gitignore). cat .python-version prints 3.15.
Step 2 · Write the library and the command
Replace the generated __init__.py with the formatter. It uses Decimal, not float, because money must round predictably: 0.1 + 0.2 is not 0.3 in binary floating point. Banker's rounding (ROUND_HALF_EVEN) is what many accounting systems expect.
cat > src/money_labels/__init__.py <<'PY'
"""Format amounts of money for display."""
from decimal import ROUND_HALF_EVEN, Decimal
__all__ = ["format_money"]
# Currency code -> (symbol, digits after the decimal point)
CURRENCIES = {
"NGN": ("₦", 2),
"KES": ("KSh", 2),
"GHS": ("GH₵", 2),
"ZAR": ("R", 2),
"USD": ("$", 2),
"EUR": ("€", 2),
"JPY": ("¥", 0),
}
def format_money(amount: str | int | Decimal, currency: str) -> str:
"""Return amount as a label such as ₦1,234.50."""
code = currency.upper()
if code not in CURRENCIES:
raise ValueError(f"unknown currency: {currency}")
symbol, places = CURRENCIES[code]
step = Decimal(1).scaleb(-places)
value = Decimal(str(amount)).quantize(step, rounding=ROUND_HALF_EVEN)
sign = "-" if value < 0 else ""
return f"{sign}{symbol}{abs(value):,.{places}f}"
PYAdd a second module for the command line. It reads an amount and a currency code, and has a --locale option that the next step wires up:
cat > src/money_labels/cli.py <<'PY'
"""The money-label command."""
import argparse
import sys
from money_labels import format_money
def main() -> None:
parser = argparse.ArgumentParser(prog="money-label")
parser.add_argument("amount", help="for example 1234.5")
parser.add_argument("currency", help="ISO 4217 code, for example NGN")
parser.add_argument("--locale", help="use Babel and this locale, for example en_NG")
args = parser.parse_args()
try:
if args.locale:
from money_labels.locales import format_for_locale
print(format_for_locale(args.amount, args.currency, args.locale))
else:
print(format_money(args.amount, args.currency))
except (ValueError, ImportError) as err:
sys.exit(f"money-label: {err}")
PYNow replace pyproject.toml with one you can read line by line:
cat > pyproject.toml <<'TOML'
[project]
name = "money-labels"
version = "0.1.0"
description = "Format amounts of money for receipts, invoices and screens."
readme = "README.md"
requires-python = ">=3.15"
dependencies = []
[project.scripts]
money-label = "money_labels.cli:main"
[build-system]
requires = ["uv_build>=0.13.10,<0.14"]
build-backend = "uv_build"
TOMLThe [project] table is the standard metadata every Python build tool reads. name and version become part of the file names you build. requires-python is the oldest Python you promise to support; installers on an older Python refuse the package. Keep it at the oldest version you actually test on, here 3.15. dependencies is what every install needs, and it is empty on purpose: the core formatter uses only the standard library.
[project.scripts] creates a command. On install, the installer writes a small money-label executable that imports money_labels.cli and calls main(). [build-system] says which tool turns the source into a wheel. Here it is uv_build, uv's own backend, pinned to the 0.13 series so a future release cannot change your builds unannounced.
Check it worked
uv run money-label 1234.5 NGN
uv run money-label 2500 jpy
uv run money-label 10 XYZ || echo "exit status $?"The first uv run creates .venv, builds the package and installs it in editable mode. The output is ₦1,234.50, then ¥2,500 (the yen has no minor unit), then money-label: unknown currency: XYZ and exit status 1.
Step 3 · Add an optional extra and a dev dependency group
Locale rules differ: Kenyan Swahili, Senegalese French and Nigerian English each place symbols and separators their own way. Babel knows these rules, but its wheel is about 10.5 MB. Users who only need the basic labels, perhaps on a prepaid data plan or a small server, should not have to download it. An optional dependency, called an extra, solves that. Write the module that uses it:
cat > src/money_labels/locales.py <<'PY'
"""Locale-aware formatting. Needs the optional 'locales' extra."""
from decimal import Decimal
def format_for_locale(amount: str, currency: str, locale: str) -> str:
try:
from babel.numbers import format_currency
except ImportError:
raise ImportError(
"locale formatting needs Babel: install money-labels[locales]"
) from None
return format_currency(Decimal(amount), currency.upper(), locale=locale)
PYThen add Babel as the locales extra, and pytest and Ruff to the dev dependency group:
uv add --optional locales "babel>=2.19,<3"
uv add --dev "pytest>=9.2,<10" "ruff>=0.17,<0.18"
cat pyproject.tomlThe two kinds of extra requirement look alike but go to different people. [project.optional-dependencies] is published: anyone can install money-labels[locales] and get Babel too. [dependency-groups] is never published. It exists only in your checkout, for the tools you need while working on the code. uv installs the dev group by default every time it syncs the project, and installs extras only when you ask:
uv run --extra locales money-label 1234.5 NGN --locale en_NG
uv run --extra locales money-label 1234.5 KES --locale sw_KECheck it worked
pyproject.toml now has a [project.optional-dependencies] table with locales = ["babel>=2.19,<3"] and a [dependency-groups] table with dev listing pytest and Ruff. The two money-label commands print something like ₦1,234.50 and Ksh 1,234.50: Babel's Swahili data writes the Kenyan shilling differently from the built-in table.
Step 4 · Test and lint with the dev group
Write tests for the formatter. They import money_labels exactly as a user would:
mkdir -p tests
cat > tests/test_format.py <<'PY'
from decimal import Decimal
import pytest
from money_labels import format_money
def test_thousands_and_two_places():
assert format_money("1234.5", "NGN") == "₦1,234.50"
def test_no_minor_unit():
assert format_money(2500, "JPY") == "¥2,500"
def test_rounds_half_to_even():
assert format_money(Decimal("0.125"), "USD") == "$0.12"
def test_negative_amount():
assert format_money("-15", "kes") == "-KSh15.00"
def test_unknown_currency():
with pytest.raises(ValueError, match="unknown currency"):
format_money("1", "XYZ")
PY
uv run pytest -q
uv run ruff checkuv run finds pytest and Ruff because the dev group is installed in .venv. Neither appears in what you publish, which you will confirm when you build.
Check it worked
pytest reports 5 passed. Ruff prints All checks passed!. If a test fails with ModuleNotFoundError: No module named 'money_labels', you ran a bare pytest from another environment; use uv run pytest from the project folder.
Step 5 · Lock the versions and read uv.lock
uv add already wrote uv.lock. Run uv lock yourself whenever you edit pyproject.toml by hand, and use --check in CI to fail when someone forgot:
uv lock
uv lock --check
grep '^name = ' uv.lock
grep -A3 '^name = "babel"' uv.lockThe lock file records one exact version of every package the project could need, with the address and SHA-256 hash of each file. It covers all extras and groups, and every platform at once: you will see colorama in the list, which pytest needs only on Windows. Your own project appears as source = { editable = "." }.
The lock file is for you and your CI, not for your users. Someone who installs money-labels gets the ranges from [project], like babel>=2.19,<3, and their installer picks versions that fit everything else in their environment. That is why a library declares ranges and an application, which nobody else installs into their own environment, can rely on the lock.
Check it worked
The list of names includes babel, iniconfig, money-labels, pluggy, pytest and ruff. The Babel block shows version = "2.19.0" or a later 2.x release, source = { registry = "https://pypi.org/simple" } and an sdist line with a sha256: hash. uv lock --check prints Resolved and a package count, with no error.
Step 6 · Build a wheel and an sdist
Build both files:
uv version
uv build
ls distuv build first makes the sdist, then builds the wheel from that sdist, not from your folder. A file that never made it into the sdist would therefore also be missing from the wheel, which catches packaging mistakes early. Look inside the wheel:
uv run python -m zipfile -l dist/money_labels-0.1.0-py3-none-any.whl
uv run python - <<'PY'
import zipfile
wheel = zipfile.ZipFile("dist/money_labels-0.1.0-py3-none-any.whl")
info = "money_labels-0.1.0.dist-info"
print(wheel.read(f"{info}/METADATA").decode())
print(wheel.read(f"{info}/entry_points.txt").decode())
PYThe wheel name reads as name, version, then py3-none-any: any Python 3, no compiled ABI, any platform. A package with C extensions would get one wheel per platform instead.
Check it worked
uv version prints money-labels 0.1.0. dist/ holds money_labels-0.1.0.tar.gz and money_labels-0.1.0-py3-none-any.whl. The wheel lists money_labels/__init__.py, cli.py and locales.py, but no tests/. METADATA contains Requires-Python: >=3.15, Provides-Extra: locales and a Requires-Dist line for Babel marked extra == 'locales', and no mention of pytest or Ruff. entry_points.txt has money-label = money_labels.cli:main under [console_scripts].
Step 7 · Install the wheel into a clean environment
The real test of a package is installing it somewhere that has never seen your source. Create a fresh environment outside the project, install only the wheel, and run the command from your home folder:
uv venv --python 3.15 ~/money-wheel-check
uv pip install --python ~/money-wheel-check ./dist/money_labels-0.1.0-py3-none-any.whl
cd ~
~/money-wheel-check/bin/money-label 99.999 GHS
~/money-wheel-check/bin/python -c "import money_labels; print(money_labels.__file__)"
~/money-wheel-check/bin/money-label 5 NGN --locale en_NG || echo "exit status $?"Without the extra, the locale option explains what is missing instead of crashing with a traceback. Now install the same wheel with the extra:
cd ~/packaging-demo/money-labels
uv pip install --python ~/money-wheel-check "./dist/money_labels-0.1.0-py3-none-any.whl[locales]"
~/money-wheel-check/bin/money-label 1234.5 NGN --locale en_NG
uv pip list --python ~/money-wheel-checkOn Windows, the command sits at money-wheel-check\Scripts\money-label.exe instead of bin/money-label.
Check it worked
The first command prints GH₵100.00 (99.999 rounds up). The import path points inside money-wheel-check/lib/python3.15/site-packages/, not into src/. The locale call without the extra prints money-label: locale formatting needs Babel: install money-labels[locales] and exit status 1. After the second install it prints ₦1,234.50, and uv pip list shows exactly two packages: babel and money-labels. No pytest, no Ruff.
Step 8 · Get ready to publish to TestPyPI
You now have files you could publish. Practise on TestPyPI, a separate copy of the index meant for trials, before you ever touch the real PyPI. These commands need an account and are not something to run on autopilot.
First, the name. money-labels may already be taken there, so change name in [project] to something unique, such as money-labels- followed by your username. uv's build backend looks for the module folder that matches the project name, so tell it the import name stays the same by adding this to pyproject.toml:
[tool.uv.build-backend]
module-name = "money_labels"Then add TestPyPI as a named index. explicit = true means uv never installs packages from it unless you ask:
cat >> pyproject.toml <<'TOML'
[[tool.uv.index]]
name = "testpypi"
url = "https://test.pypi.org/simple/"
publish-url = "https://test.pypi.org/legacy/"
explicit = true
TOMLCreate an API token in your TestPyPI account settings. Read it into an environment variable with a prompt that does not echo it, so it never lands in your shell history or a file, rebuild, publish, and clear the variable:
rm -rf dist
uv build
printf "TestPyPI token: "
read -rs UV_PUBLISH_TOKEN
echo
export UV_PUBLISH_TOKEN
uv publish --index testpypi
unset UV_PUBLISH_TOKENTwo things to know before you publish anything. A version number can be used only once: after 0.1.0 is uploaded, even a deleted release cannot be replaced, so bump it with uv version --bump patch and rebuild. And add a license and authors to [project] before a real release, so people know who made the package and how they may use it.
Check it worked
Before publishing, uv build still produces the two files under your new name, for example money_labels_ada-0.1.0-py3-none-any.whl. After uv publish, your project page appears at https://test.pypi.org/project/<your-name>/ with the description and version from pyproject.toml.
Step 9 · Clean up
Remove the demo project and the check environment. Python and uv stay installed, and uv's download cache stays too, so a later rebuild does not download Babel again:
cd ~
rm -rf ~/packaging-demo ~/money-wheel-checkCheck it worked
ls ~/packaging-demo reports No such file or directory.
Next steps
- Grow the package past three files: split Python code into modules.
- Write fuller tests for it: test Python code with pytest.
- Let the type checker read your annotations: add type hints and check them with mypy.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials