Skip to content

Comments

tomlrt exposes comments at every level of a document: end-of-line, above an entry, above a section header, and at the top or bottom of the file.

End-of-line comments

Table.comments is a live MutableMapping[str, str] keyed by entry name. Assign a string to set or replace the comment; del removes it entirely.

doc = tomlrt.loads("""
[server]
host = "localhost"  # default
port = 8080
""")

server = doc.table("server")
server.comments["port"] = "override with $PORT"
del server.comments["host"]                 # remove the comment entirely

print(tomlrt.dumps(doc))
# [server]
# host = "localhost"
# port = 8080 # override with $PORT

Comments above an entry

Table.leading_comments is keyed by entry name and stores a tuple of bare comment lines (no leading #):

server.leading_comments["port"] = (
    "Port the server listens on.",
    "Defaults to 8080.",
)

Section header comments

Table.header_comment is the end-of-line comment on the [section] line itself; Table.header_leading_comments is the run of # … lines immediately above it:

server.header_comment = "HTTP listener"
server.header_leading_comments = ("Server configuration.",)

Array-item comments

Array exposes comments and leading_comments keyed by integer index:

tags = doc.array("tags")
tags.comments[0] = "primary"
tags.leading_comments[1] = ("alternate",)

Document preamble and epilogue

The top-of-file and bottom-of-file comment blocks are reachable via Document.preamble and Document.epilogue — both are tuples of bare comment lines, and both have setters that replace the entire block. Assign () to clear.

doc.preamble = ("Generated by build.py — do not edit.",)
doc.epilogue = ("end of file",)

A "preamble" is the run of # … lines that opens the file and is blank-line-separated from anything below. Comments that sit directly above the first key (no blank line) are leading comments of that key, not preamble.