Batu Lab NotesPractical developer guides

Handle invalid TOML in a readiness scan

By Batu ยท English technical notes

Also published in our Blogger archive.

Direct answer

Invalid TOML should become a distinct unavailable result, not a guessed version. tomllib.loads raises TOMLDecodeError; the helper catches only that parsing failure and returns None. A valid [project] document then demonstrates the supported static path.

The malformed header is the edge case. It contains characters resembling metadata but cannot be interpreted safely. Searching that raw text for version would turn corruption into a false signal. The assertions preserve the distinction between invalid syntax and a verified string value.

This reader does not repair TOML, load a file, support dynamic package metadata, or inspect tool-specific version keys. Those choices belong in separately documented branches. The narrow response is useful because a caller can request human review instead of receiving invented data.

Complete example

import tomllib


def read_version(text: str) -> str | None:
    try:
        document = tomllib.loads(text)
    except tomllib.TOMLDecodeError:
        return None
    value = document.get("project", {}).get("version")
    return value if isinstance(value, str) else None

assert read_version("[project\nversion =") is None
assert read_version("[project]\nversion = \"1.0.0\"") == "1.0.0"
print("invalid=unavailable valid=1.0.0")

Expected stdout:

invalid=unavailable valid=1.0.0

Sources

- Official API documentation

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.