Comments¶
Read and write comments separately from values. Comment strings do not include
the leading #.
End-of-line comments¶
Use comments like a dictionary keyed by entry name.
Assign a string to set or replace a comment; del removes it.
import tomlrt
doc = tomlrt.loads("""\
[server]
host = "localhost" # default
port = 8080
""")
server = doc.table("server")
server.comments["port"] = "override with $PORT"
del server.comments["host"]
print(tomlrt.dumps(doc))
Comments above an entry¶
leading_comments reads or replaces the comment
lines immediately above an entry, with no intervening blank line:
Section header comments¶
Use header_comment for a comment on the
[section] line itself, and
header_leading_comments for comments
immediately above it:
Array-item comments¶
Arrays have the same comments and
leading_comments properties, keyed by item
index:
Inline-table comments¶
TOML 1.1 allows inline tables to span multiple lines and carry comments. Use the same comment properties as for sections:
import tomlrt
doc = tomlrt.loads('pkg = { name = "tomlrt", version = "0.1" }\n')
pkg = doc.table("pkg")
pkg.comments["name"] = "the package name"
print(tomlrt.dumps(doc))
Adding a comment makes a single-line table or array multi-line automatically. See Layout to control this explicitly.
Inline tables have no section header, so the header_* properties are not
available on them.
Blank-separated leading blocks¶
Use leading_block or
header_leading_block to include comments
separated by blank lines. These return a tuple of comment strings, with None
for each blank line. For example:
assert doc["b"].header_leading_block == (None, "Configuration", None)
doc["b"].header_leading_block = ("Configuration", None, "Section b")
Comment blocks travel with their entry when copied, moved, or sorted. The document preamble and epilogue stay with the document.
Document preamble and epilogue¶
Use Document.preamble and
Document.epilogue for opening and closing file
comments. Assignment replaces the whole block; () clears it.
A "preamble" is the document's opening comment paragraph — the run of # …
lines before the first blank line.
Comments below that blank line belong to the first key or section, not the
preamble.
The "epilogue" is the comment block after the last entry. It can include blank
lines, represented by None.