Thanks to Brett, Ofek, Paul and Courtney for their work on the two PEPs.
I put together a quick parser yesterday and I wanted to check it against the reference implementation given in the pep. However it seems that the reference implementation for reading a block doesn’t work and gives an AttributeError unless I’m missing something?
Reference Code
import re
import tomllib
REGEX = r'(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$'
def read(script: str) -> dict | None:
name = 'pyproject'
matches = list(
filter(lambda m: m.group('type') == name, re.finditer(REGEX, script))
)
if len(matches) > 1:
raise ValueError(f'Multiple {name} blocks found')
elif len(matches) == 1:
return tomllib.loads(matches[0])
else:
return None
sample = """
# /// pyproject
# [run]
# requires-python = ">=3.11"
# dependencies = [
# "requests<3",
# "rich",
# ]
# ///
"""
print(read(sample))
Output:
AttributeError: 're.Match' object has no attribute 'replace'
It looks like it needs to extract the block from the re.match and remove the "# " from each line before passing to tomllib.loads. Something like:
elif len(matches) == 1:
content = matches[0].group("content")
data = "\n".join(line[2:] for line in content.split("\n"))
return tomllib.loads(data)