Packaging Exercises
Each exercise is a small piece of logic that pip, uv or Poetry run every day, written as a pure function with the tests already in place. Run the starter first: it prints wrong answers (None, empty lists), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real session to repair.
Exercise 1: Normalise a project name
Topics: How pip install Works, pip freeze, list & show
Indexes treat Charset_Normalizer, charset.normalizer and charset-normalizer as the same project. The rule (PEP 503): lowercase, and replace every run of -, _ and . with a single -.
def normalize(name):
# TODO: lowercase and collapse runs of "-", "_", "." into "-"
return None
for n in ["Charset_Normalizer", "zope.interface", "Django", "markdown--it__py", "ruamel.yaml.clib"]:
print(f"{n:<20} -> {normalize(n)}")Charset_Normalizer -> None
zope.interface -> None
Django -> None
markdown--it__py -> None
ruamel.yaml.clib -> None
Expected output:
Charset_Normalizer -> charset-normalizer
zope.interface -> zope-interface
Django -> django
markdown--it__py -> markdown-it-py
ruamel.yaml.clib -> ruamel-yaml-clibShow solution
import re
def normalize(name):
return re.sub(r"[-_.]+", "-", name).lower()Exercise 2: Parse a wheel filename
Topics: Wheel Tags & Compatibility
Split a wheel filename into name, version and the set of tags it supports. Each of the three tag parts may hold several values separated by dots; the tag set is every combination. Ignore the optional build number (a filename with six dash-separated parts).
def parse_wheel(filename):
# TODO: strip ".whl", split on "-", expand the dotted tag parts into "py-abi-plat" strings
return None, None, []
for f in ["six-1.17.0-py2.py3-none-any.whl",
"attrs-26.1.0-py3-none-any.whl",
"charset_normalizer-3.5.2-cp313-cp313-manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl",
"fastmath-2.0-1-cp313-cp313-win_amd64.whl"]:
name, version, tags = parse_wheel(f)
print(name, version, sorted(tags))None None []
None None []
None None []
None None []
Expected output:
six 1.17.0 ['py2-none-any', 'py3-none-any']
attrs 26.1.0 ['py3-none-any']
charset_normalizer 3.5.2 ['cp313-cp313-manylinux_2_17_x86_64', 'cp313-cp313-manylinux_2_28_x86_64']
fastmath 2.0 ['cp313-cp313-win_amd64']Show solution
from itertools import product
def parse_wheel(filename):
parts = filename[:-4].split("-")
if len(parts) == 6: # name-version-build-py-abi-plat
del parts[2]
name, version, py, abi, plat = parts
tags = {f"{p}-{a}-{pl}" for p, a, pl in product(py.split("."), abi.split("."), plat.split("."))}
return name, version, tagsExercise 3: Expand a compatible-release specifier
Topics: PEP 440 Versions & Specifiers
~=X.Y means >=X.Y, ==X.*; ~=X.Y.Z means >=X.Y.Z, ==X.Y.*. Write expand(spec) returning the equivalent pair as a string, and matches(version, spec) for simple numeric versions. A single-part version (~=2) is invalid: return None.
def expand(spec):
# TODO: drop the last release component for the "==" prefix
return None
def v(s): return tuple(int(x) for x in s.split("."))
def matches(version, spec):
# TODO: use the expanded form: version >= base and version starts with the prefix
return False
for spec in ["~=2.31", "~=2.31.0", "~=1.4.5.2", "~=2"]:
print(f"{spec:<10} -> {expand(spec)}")
for version in ["2.30.9", "2.31.0", "2.34.2", "3.0.0"]:
print(version, matches(version, "~=2.31"), matches(version, "~=2.31.0"))~=2.31 -> None
~=2.31.0 -> None
~=1.4.5.2 -> None
~=2 -> None
2.30.9 False False
2.31.0 False False
2.34.2 False False
3.0.0 False False
Expected output:
~=2.31 -> >=2.31, ==2.*
~=2.31.0 -> >=2.31.0, ==2.31.*
~=1.4.5.2 -> >=1.4.5.2, ==1.4.5.*
~=2 -> None
2.30.9 False False
2.31.0 True True
2.34.2 True False
3.0.0 False FalseShow solution
def expand(spec):
base = spec[2:]
parts = base.split(".")
if len(parts) < 2:
return None
return f">={base}, =={'.'.join(parts[:-1])}.*"
def matches(version, spec):
base = spec[2:]
prefix = v(base)[:-1]
return v(version) >= v(base) and v(version)[:len(prefix)] == prefixExercise 4: Read a requirements file
Topics: requirements.txt & Constraints Files
Return a list of (name, specifier, marker) tuples. Skip blank lines, comments (whole-line and trailing #) and option lines starting with -. The marker is the text after ;, or None. Normalise names as in exercise 1.
import re
text = """
# runtime
requests>=2.31,<3 # HTTP
Rich==13.9.4
-c constraints.txt
colorama ; sys_platform == "win32"
--index-url https://example.com/simple/
attrs
"""
def parse(text):
result = []
# TODO: go line by line
return result
for item in parse(text):
print(item)
print(len(parse(text)), "requirements")0 requirements
Expected output:
('requests', '>=2.31,<3', None)
('rich', '==13.9.4', None)
('colorama', '', 'sys_platform == "win32"')
('attrs', '', None)
4 requirementsShow solution
def parse(text):
result = []
for line in text.splitlines():
line = line.split(" #", 1)[0].strip()
if not line or line.startswith(("#", "-")):
continue
req, _, marker = line.partition(";")
m = re.match(r"([A-Za-z0-9._-]+)\s*(.*)", req.strip())
name = re.sub(r"[-_.]+", "-", m.group(1)).lower()
result.append((name, m.group(2).strip(), marker.strip() or None))
return resultExercise 5: Lock a graph
Topics: Dependency Resolution & Conflicts, uv.lock
Given an index of versions with their dependencies (all specifiers are >=), produce a lock: for each package reachable from the root requirements, the newest version that satisfies every >= requirement on it. (No backtracking is needed for >= only.) Return the lock sorted by name.
index = {
"app-deps": {},
"requests": {"2.31.0": {"urllib3": "1.26", "idna": "2.5"}, "2.34.2": {"urllib3": "1.26", "idna": "2.5"}},
"urllib3": {"1.26.0": {}, "2.8.0": {}},
"idna": {"3.20": {}},
"rich": {"15.0.0": {"pygments": "2.13"}},
"pygments": {"2.21.0": {}},
}
roots = {"requests": "2.31", "rich": "13"}
def v(s): return tuple(int(x) for x in s.split("."))
def lock(roots):
# TODO: walk the graph from roots, choose the newest version >= every lower bound seen
return {}
for name, version in lock(roots).items():
print(f"{name}=={version}")
print(len(lock(roots)), "packages locked")0 packages locked
Expected output:
idna==3.20
pygments==2.21.0
requests==2.34.2
rich==15.0.0
urllib3==2.8.0
5 packages lockedShow solution
def lock(roots):
bounds, chosen, todo = {}, {}, list(roots.items())
while todo:
name, low = todo.pop()
bounds[name] = max(bounds.get(name, "0"), low, key=v)
best = max((ver for ver in index[name] if v(ver) >= v(bounds[name])), key=v)
if chosen.get(name) != best:
chosen[name] = best
todo.extend(index[name][best].items())
return dict(sorted(chosen.items()))Exercise 6: Repair a broken build
Topics: pyproject.toml, Build Backends, Entry Points
A colleague's project fails to build. Read the error and fix pyproject.toml (not the code) so that the session builds a wheel and the tadstat command prints mean = 2.5.
python3 -m venv .venv && . .venv/bin/activate
mkdir -p tadstat/src/tadstat && cd tadstat
cat > pyproject.toml <<'TOML'
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "tadstat"
requires-python = ">=3.13"
[project.scripts]
tadstat = "tadstat.cli:main"
TOML
cat > src/tadstat/__init__.py <<'PY'
__version__ = "0.3.0"
def mean(xs): return sum(xs) / len(xs)
PY
cat > src/tadstat/cli.py <<'PY'
from tadstat import mean
def main(): print("mean =", mean([1, 2, 3, 4]))
PY
pip install -q . 2>&1 | grep -E '^ *(ValueError|ERROR)'
tadstat 2>&1 ValueError: Field `project.version` can only be resolved dynamically if `version` is in field `project.dynamic`
/w/main.sh: line 24: tadstat: command not found
Show solution
The [project] table has no version, and the version isn't declared dynamic. Either add version = "0.3.0", or keep the single source of truth in __init__.py and let hatchling read it:
[project]
name = "tadstat"
dynamic = ["version"]
requires-python = ">=3.13"
[tool.hatch.version]
path = "src/tadstat/__init__.py"With that change, pip install . builds and installs the wheel, and tadstat prints mean = 2.5.
Test yourself
Which two names refer to the same project on an index?
- requests and request
- Charset_Normalizer and charset-normalizer
- attrs and attr
- pytest and py.test
How many tags does six-1.17.0-py2.py3-none-any.whl declare?
- 1
- 2
- 3
- 4