spec.locate

spec.locate(path, key, value=None, top_level=False)

Find the line of a TOML key such as id = "C-1" in a file.

tomllib keeps no positions, so this is a line-oriented text search. It looks for a line that holds the key, an equals sign and the quoted value, for example module = "core". The key may be bare or quoted. Without value any line with the key matches. A key that appears on several lines is ambiguous, so the search then returns None rather than a possibly wrong line. With top_level only the lines before the first table header ([x] or [[x]]) are searched, so a unit-level key such as evaluations is not confused with the same key of an [[intent]] item.

Parameters

Name Type Description Default
path Path | str The TOML file. required
key str The key, for example "id" or "unit". required
value str | None The string value, without quotes. None matches the key alone. None
top_level bool Search only the part of the file before the first table header. False

Returns

Name Type Description
int | None int | None: The 1-based line number, or None if the file cannot be read, the line is missing or it is not unique.

Examples

from pathlib import Path
from tempfile import TemporaryDirectory

from spotregen import locate, make_sample_repo

with TemporaryDirectory() as tmp:
    root = make_sample_repo(Path(tmp) / "demo")
    unit = root / "regen" / "units" / "core.calc.toml"
    print(locate(unit, "unit", "samplepkg.core.calc"))
    print(locate(unit, "unit", "no.such.unit"))
    print(locate(unit, "evaluations"), locate(unit, "evaluations", top_level=True))
1
None
None 8