Python Labs · Lab 1 of 6
A Modern Python Project: uv, src Layout, Tests and Linting
Set up a Python project the way professional teams do: uv for environments and dependencies, a src layout, a lockfile, pytest for tests and ruff for linting and formatting, all driven from pyproject.toml.
- Environment
- Local
- Level
- Beginner
- Time
- About 30 min
- Cost
- Free
You will build
A small, tested package (shopcalc) that adds up orders with exact money arithmetic, with one command each to
test, lint, format and run it, and a lockfile that makes every install identical.
Before you start
uv installed (
uv --version); see docs.astral.sh/uv for the one-line installerGit
`uv` replaces `pip`, `venv`, `pip-tools` and `pipx` with one fast tool. It creates the virtual environment,
resolves dependencies, writes a lockfile and runs your commands inside the environment.
The output below was recorded with uv 0.13.10 and Python 3.12. Newer versions print newer version numbers and
timings; everything else should match. The finished-project download leaves out uv.lock: uv sync creates it.
Project structure
shopcalc/
├── .gitignore
├── .python-version # the Python version uv uses here
├── README.md
├── pyproject.toml # metadata, dependencies, tool settings
├── uv.lock # exact versions of every dependency (commit it)
├── src/
│ └── shopcalc/
│ ├── __init__.py
│ └── pricing.py
└── tests/
└── test_pricing.py
Steps
-
1Create the project
--packagecreates a src layout: the code lives insrc/shopcalc/and is installed into the environment, so tests import the package exactly as users will. uv also starts a Git repository.Run uv init --package shopcalc cd shopcalcExpected output
Initialized project `shopcalc` at `.../shopcalc`
-
2Look at what uv created
Run find . -not -path './.git*' | sortExpected output
. ./pyproject.toml ./.python-version ./README.md ./src ./src/shopcalc ./src/shopcalc/__init__.py
Check:pyproject.tomlhas a[project.scripts]entry:shopcalc = "shopcalc:main". -
3Add the development tools
--devputs pytest and ruff in adevdependency group: installed for you, never shipped to users. The firstuvcommand also creates.venv/anduv.lock.Run uv add --dev pytest ruffExpected output
Using CPython 3.12.3 interpreter at: /usr/bin/python3.12 Creating virtual environment at: .venv Resolved 8 packages in 93ms ... Installed 7 packages in 3ms + iniconfig==2.3.1 + packaging==26.4 + pluggy==1.7.0 + pygments==2.21.0 + pytest==9.2.0 + ruff==0.17.6 + shopcalc==0.1.0 (from file:///.../shopcalc)
-
4See why money needs Decimal
Binary floats can't represent most decimal fractions exactly. Never use them for money.
Run python3 -c "print(0.1 + 0.2)"Expected output
0.30000000000000004
-
5Write the module
Decimalbuilt from strings is exact;quantizerounds to cents the way accountants expect (half up). Invalid input raises an error instead of producing a wrong total.src/shopcalc/pricing.py """Order totals with exact money arithmetic.""" from decimal import ROUND_HALF_UP, Decimal CENT = Decimal("0.01") def line_total(unit_price: str, quantity: int) -> Decimal: """Price of one order line, rounded to cents.""" if quantity < 0: raise ValueError("quantity must not be negative") return (Decimal(unit_price) * quantity).quantize(CENT, rounding=ROUND_HALF_UP) def order_total(lines: list[tuple[str, int]], tax_rate: str = "0") -> Decimal: """Sum of all lines plus tax, rounded to cents.""" subtotal = sum((line_total(price, qty) for price, qty in lines), Decimal("0.00")) tax = (subtotal * Decimal(tax_rate)).quantize(CENT, rounding=ROUND_HALF_UP) return subtotal + tax -
6Use it from the command entry point
src/shopcalc/__init__.py from shopcalc.pricing import order_total def main() -> None: total = order_total([("19.99", 2), ("5.00", 1)], tax_rate="0.08") print(f"Order total: {total}") -
7Write the tests
parametrizeruns one test with several inputs, so each case is listed once and reported separately.tests/test_pricing.py from decimal import Decimal import pytest from shopcalc.pricing import line_total, order_total def test_line_total_rounds_to_cents(): assert line_total("0.333", 3) == Decimal("1.00") @pytest.mark.parametrize( ("lines", "tax_rate", "expected"), [ ([("19.99", 2), ("5.00", 1)], "0.08", "48.58"), ([("0.10", 1), ("0.20", 1)], "0", "0.30"), ([], "0.08", "0.00"), ], ) def test_order_total(lines, tax_rate, expected): assert order_total(lines, tax_rate) == Decimal(expected) def test_negative_quantity_is_rejected(): with pytest.raises(ValueError, match="negative"): line_total("1.00", -1) -
8Configure ruff and pytest in pyproject.toml
One file holds the project's metadata, dependencies and tool settings. The ruff rule sets add import sorting (
I), common bugs (B), modern syntax (UP) and simplifications (SIM).pyproject.toml [project] name = "shopcalc" version = "0.1.0" description = "Order totals with exact money arithmetic" readme = "README.md" authors = [ { name = "Your Name", email = "[email protected]" } ] requires-python = ">=3.12" dependencies = [] [project.scripts] shopcalc = "shopcalc:main" [build-system] requires = ["uv_build>=0.13.10,<0.14.0"] build-backend = "uv_build" [dependency-groups] dev = [ "pytest>=9.2.0", "ruff>=0.17.6", ] [tool.ruff] line-length = 100 target-version = "py312" [tool.ruff.lint] select = ["E", "F", "I", "B", "UP", "SIM"] [tool.pytest.ini_options] testpaths = ["tests"] addopts = ["-ra", "--strict-markers"] -
9Run the tests
Run uv run pytestExpected output
============================= test session starts ============================== platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0 rootdir: .../shopcalc configfile: pyproject.toml testpaths: tests collected 5 items tests/test_pricing.py ..... [100%] ============================== 5 passed in 0.01s ===============================
Check:5 passed.uv runmakes sure the environment matches the lockfile before running. -
10Run the program
Run uv run shopcalcExpected output
Order total: 48.58
-
11Lint and check formatting
Run uv run ruff check uv run ruff format --checkExpected output
All checks passed! 4 files already formatted
-
12Let ruff catch a mistake
Add
import osat the top ofpricing.py(it isn't used), then lint again and let ruff fix it.Run uv run ruff check uv run ruff check --fixExpected output
F401 [*] `os` imported but unused --> src/shopcalc/pricing.py:3:8 | 1 | """Order totals with exact money arithmetic.""" 2 | 3 | import os | ^^ 4 | from decimal import ROUND_HALF_UP, Decimal | help: Remove unused import: `os` ... Found 1 error. [*] 1 fixable with `--fix`. Found 1 error (1 fixed, 0 remaining).
Check:ruff checkexits with status 1 before the fix and 0 after it, which is what makes CI fail or pass. -
13Install exactly what the lockfile says
--lockedfails ifpyproject.tomlanduv.lockdisagree, instead of silently updating the lock. This is the command CI and Docker builds use.Run uv sync --lockedExpected output
Resolved 8 packages in 1ms Checked 7 packages in 0.15ms
-
14Check what Git will commit
Run git status --shortExpected output
?? .gitignore ?? .python-version ?? README.md ?? pyproject.toml ?? src/ ?? tests/ ?? uv.lock
Check:.venv/is not listed (uv's.gitignoreexcludes it) anduv.lockis — commit it.
In production
The tools and layout in this lab are what production Python teams use. What changes is that nothing depends on someone remembering to run a command.
What changes
| In this lab | In production |
|---|---|
You run pytest and ruff by hand |
CI runs uv sync --locked, ruff check, ruff format --check and pytest on every pull request; merging needs green checks |
| Whatever Python is on your laptop | requires-python matches the runtime you deploy, and CI tests that exact version (a matrix for libraries) |
uv add when you need a package |
Automated update pull requests (Dependabot or Renovate) that run the full test suite before anyone merges them |
| A handful of ruff rules | A rule set the team agreed on, the formatter enforced, and a pre-commit hook so problems never reach review |
Decimal in one function |
A project rule: money is Decimal in code and integer cents or NUMERIC in the database, never float |
Why the src layout matters
With a flat layout, tests can import your code straight from the folder even if packaging is broken. With
src/, tests import the installed package, so a missing file or wrong package configuration fails in CI
instead of in a user's install.
Production checklist
uv.lockis committed and every automated install usesuv sync --locked- Lint, format check and tests run in CI on every pull request; the main branch is protected
requires-pythonmatches the production runtime- Dependency updates are automated and reviewed
- No secrets,
.venv/or build output in Git - Money and other exact values never use
float
Learn the concepts
- Python pip and Virtual Environments · Python Tutorial
- Python Modules and Imports · Python Tutorial
- Python Testing with pytest · Python Tutorial
- Python Numbers · Python Tutorial
- Testing in Practice · Course