
Read the ID Card
pyproject.toml is written in TOML, a simple config format. It has
[tables] with key = value pairs inside. Since Python 3.11, the
standard library can read it with tomllib:
import tomllib
data = tomllib.loads(text) # from a string
with open("pyproject.toml", "rb") as f:
data = tomllib.load(f) # from a file (binary mode!)
data["project"]["name"] # 'lantern-tools'
TOML tables become nested dicts. [project.scripts] ends up as
data["project"]["scripts"]. The [project.scripts] table creates
command-line commands: lantern = "lantern_tools.cli:main" means typing
lantern runs main() from lantern_tools/cli.py.
Dependencies are requirement strings such as "rich>=13". That
means the name rich, at version 13 or newer.
Pip tip:
tomllibcan only read TOML. To write it, you'd need a third-party package such astomli-w.
Assignment
Write summarize_project(text) that parses the TOML text and returns a
dict with:
"name"and"version"from[project]"python": therequires-pythonvalue, or"any"if missing"deps": dependency names only (use thedep_namehelper), or[]"commands": the sorted names in[project.scripts], or[]
If there is no [project] table, raise ValueError.
Write summarize_project(text) that parses the TOML text and returns a
dict with:
"name"and"version"from[project]"python": therequires-pythonvalue, or"any"if missing"deps": dependency names only (use thedep_namehelper), or[]"commands": the sorted names in[project.scripts], or[]
If there is no [project] table, raise ValueError.
Press Run to try your code, then Check to test it.