Skip to content

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))
[server]
host = "localhost"
port = 8080 # override with $PORT

Comments above an entry

leading_comments reads or replaces the comment lines immediately above an entry, with no intervening blank line:

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

Section header comments

Use header_comment for a comment on the [section] line itself, and header_leading_comments for comments immediately above it:

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

Array-item comments

Arrays have the same comments and leading_comments properties, keyed by item index:

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

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))
pkg = {
    name = "tomlrt", # the package name
    version = "0.1",
}

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:

[a]
x = 1

# Configuration

[b]
y = 2
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.

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

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.