API reference¶
Details of the public classes, methods, and options.
Stability¶
Import public names from tomlrt. They follow semantic versioning:
| Symbol | Kind |
|---|---|
loads, load |
function |
dumps, dump |
function |
Document, Table, Array, AoT |
class |
FormatOptions |
class |
QuoteStyle |
enum |
TomlInput |
type alias |
TOMLError, TOMLParseError |
exception |
Modules prefixed with _ are internal and may change without notice.
Top-level functions¶
load ¶
Parse a TOML document from a binary file-like object.
The file must be opened in binary mode (open(path, "rb")).
dumps ¶
Serialize a document or mapping to a TOML string.
Plain mappings are written using the same rules as
Document(data).
dump ¶
Formatting¶
QuoteStyle ¶
Preferred string and quoted-key spelling for format().
FormatOptions ¶
Canonical formatting options shared by all format() methods.
normalize_comments rewrites comment text to canonical # body form
and strips trailing whitespace. Layout around comments is canonicalised
regardless.
indent is the number of spaces added at each nested multiline array
or inline-table level.
eol_comment_spaces is the number of spaces inserted before supported
end-of-line comments.
multiline_trailing_comma controls whether the final item in a multiline
array or inline table has a comma.
quote_style prefers single or double quotes for strings and quoted
keys when neither form requires more escapes. QuoteStyle.PRESERVE
leaves the original spelling unchanged.
Containers¶
Document ¶
Top-level TOML document.
A Document is the root of a parsed TOML
file. It is a dict subclass and can be passed wherever a
dict or Mapping is expected.
__init__ ¶
Return a fresh empty document, optionally populated from data.
With a mapping:
- nested mappings become standard
[section]blocks (not inline tables); - lists of mappings become
[[array.of.tables]]blocks; - everything else is set with ordinary key-value assignment.
Input values are copied. Existing tomlrt tables and arrays retain their form, comments, and formatting in the copy.
To add a newly created table or array without copying, assign it
instead: doc[k] = table. See
Editing documents.
render ¶
Serialize the document back to a TOML string.
Equivalent to tomlrt.dumps(self).
table ¶
Return the value at key typed as a Table.
key may be a single name, a dotted-string path, or a
sequence of names.
aot ¶
Return the value at key typed as an array-of-tables (AoT).
entry ¶
Resolve a (possibly dotted) key path; raises KeyError if missing.
Raises TypeError if descent passes through a non-table, and
ValueError for an empty path or a path with empty segments.
get_entry ¶
Like entry(key) but returns default if the path is missing.
install ¶
Set value at the (possibly dotted) path.
Creates missing parent tables. Existing parents keep their form
for scalar and inline values. When called on a document or a section
in a document, installing a section or AoT converts inline parent
tables to sections as needed.
Returns the stored value or live view. Rejected paths and values leave the document unchanged.
ensure_table ¶
Return the table at key, creating it if missing.
Accepts a dotted path or a sequence of key names. Existing tables
keep their form. Missing tables inside inline tables are inline;
elsewhere, a section is created with a header such as [a.b.c].
Raises TOMLError if a value along the path is not a table.
promote_inline is deprecated and ignored. Use promote_inline()
to request conversion explicitly.
promote_inline ¶
Convert an inline-table entry at key into a section header.
Returns the live view at key after promotion. Raises
KeyError if the key is missing, or TOMLError if it
doesn't refer to an inline-style table.
promote_array ¶
Convert an array-of-inline-tables at key into an AoT.
Returns the live AoT view at key. Raises KeyError if the
key is missing, or TOMLError if it refers to a non-array, an
empty array, or an array with non-inline-table elements.
preamble
deletable
property
writable
¶
The document's opening comment paragraph, as bare comment texts.
The preamble is the run of # … lines before the first blank
line. Comments below that blank line belong to the first key or
section (its leading_comments / leading_block), not the
preamble.
Setting replaces the preamble with a sequence of comment texts
(without the leading #); assign () to remove. Line
terminators within a comment are rejected.
epilogue
deletable
property
writable
¶
Comment block at the very end of the document.
Comments after the last entry, without the leading #, with
None for each blank line, in source order.
Setting replaces the epilogue with the same shape; assign () to
remove. Line terminators within a comment are rejected.
Raises TOMLError if called with a non-empty
value on a document with no entries.
comments
property
¶
End-of-line comments, keyed by entry name.
Comment strings do not include the leading #. Adding comments
to a single-line inline table makes it multi-line.
leading_comments
property
¶
Comment lines immediately above each key, keyed by entry name.
Returns a tuple of strings without the leading #. Only comments
with no blank line between them and the key are included.
For comments separated by blank lines, see
leading_block.
Adding comments makes a single-line inline table multi-line.
leading_block
property
¶
Comments and blank lines above each key, keyed by entry name.
Each value is a tuple of comment strings without the leading #,
with None for each blank line, in source order.
For the document's first key, the opening comment paragraph is the
Document.preamble and is omitted here;
this block starts after the first blank line.
Comments on an inline table's opening brace are not part of the first entry's block.
sort ¶
Sort direct child keys in place, keeping comments and formatting.
Accepts keyword-only key and reverse, like list.sort.
Key-value lines stay before section and array-of-tables headers
so they still belong to the same table. Keys are sorted in groups:
those with only key-value lines, those with both lines and headers,
then those with only headers. key and reverse apply within
each group.
format ¶
Canonicalise this container's formatting in place.
Normalizes spacing, indentation, and blank lines in this table and its children. Comments are retained, and multi-line values stay multi-line. Newlines use the document's line endings.
Use FormatOptions(normalize_comments=False) to leave comment
text untouched.
Add a newly created table to a document before formatting it.
For inline tables defined by dotted keys, format the enclosing
inline table, not an inner table such as a in {a.b = 1}.
Unsupported tables raise TOMLError.
Table ¶
A logical TOML table.
Every nested mapping in a document is a Table.
Table is a dict subclass, so isinstance(t, dict) holds
and it can be passed wherever a dict or Mapping is expected.
The same Table class backs both standard [section] blocks
and inline {x = 1} tables. Use is_inline
to tell them apart when walking a parsed document.
section
classmethod
¶
Return a standard-section table, optionally populated from mapping.
Assign the result to install a [k] block:
doc[k] = Table.section({"x": 1})
inline
classmethod
¶
Return an inline table, optionally populated from mapping.
Assign the result to install a {x = 1} value:
doc[k] = Table.inline({"x": 1})
multiline
property
writable
¶
Whether this inline table is laid out across multiple lines.
Raises TOMLError on a non-inline table.
set_multiline ¶
Switch this inline table between single-line and multi-line form.
When laying out multi-line, entries are indented by indent
spaces and the closing brace lines up with the row the table
starts on.
Raises TOMLError on a non-inline table, and
when collapsing a multi-line table that carries comments anywhere
in it (they would have nowhere to live on one line).
Returns self for chaining.
table ¶
Return the value at key typed as a Table.
key may be a single name, a dotted-string path, or a
sequence of names.
aot ¶
Return the value at key typed as an array-of-tables (AoT).
entry ¶
Resolve a (possibly dotted) key path; raises KeyError if missing.
Raises TypeError if descent passes through a non-table, and
ValueError for an empty path or a path with empty segments.
get_entry ¶
Like entry(key) but returns default if the path is missing.
install ¶
Set value at the (possibly dotted) path.
Creates missing parent tables. Existing parents keep their form
for scalar and inline values. When called on a document or a section
in a document, installing a section or AoT converts inline parent
tables to sections as needed.
Returns the stored value or live view. Rejected paths and values leave the document unchanged.
ensure_table ¶
Return the table at key, creating it if missing.
Accepts a dotted path or a sequence of key names. Existing tables
keep their form. Missing tables inside inline tables are inline;
elsewhere, a section is created with a header such as [a.b.c].
Raises TOMLError if a value along the path is not a table.
promote_inline is deprecated and ignored. Use promote_inline()
to request conversion explicitly.
promote_inline ¶
Convert an inline-table entry at key into a section header.
Returns the live view at key after promotion. Raises
KeyError if the key is missing, or TOMLError if it
doesn't refer to an inline-style table.
promote_array ¶
Convert an array-of-inline-tables at key into an AoT.
Returns the live AoT view at key. Raises KeyError if the
key is missing, or TOMLError if it refers to a non-array, an
empty array, or an array with non-inline-table elements.
header_comment
deletable
property
writable
¶
The end-of-line comment on this table's section header, or None.
Tables with no header of their own return None; setting a comment
on them raises TOMLError.
Inline tables do not support this property.
header_leading_comments
deletable
property
writable
¶
Comment lines immediately above this table's section header.
Tables with no header of their own return (); setting comments
on them raises TOMLError.
Inline tables do not support this property.
For comments separated from the header by blank lines, see
header_leading_block.
header_leading_block
deletable
property
writable
¶
Comments and blank lines above this table's section header.
A tuple of comment strings without the leading #, with None
for each blank line, in source order.
Tables with no header of their own return (); setting comments
on them raises TOMLError.
Inline tables do not support this property.
For the document's first section, the opening comment paragraph is
the Document.preamble and is omitted
here; this block starts after the first blank line.
comments
property
¶
End-of-line comments, keyed by entry name.
Comment strings do not include the leading #. Adding comments
to a single-line inline table makes it multi-line.
leading_comments
property
¶
Comment lines immediately above each key, keyed by entry name.
Returns a tuple of strings without the leading #. Only comments
with no blank line between them and the key are included.
For comments separated by blank lines, see
leading_block.
Adding comments makes a single-line inline table multi-line.
leading_block
property
¶
Comments and blank lines above each key, keyed by entry name.
Each value is a tuple of comment strings without the leading #,
with None for each blank line, in source order.
For the document's first key, the opening comment paragraph is the
Document.preamble and is omitted here;
this block starts after the first blank line.
Comments on an inline table's opening brace are not part of the first entry's block.
has_header ¶
Whether key or its children contain a [table] or [[table]].
For example, [a.b] makes doc.has_header("a") true, even
though a has no header of its own. Returns False for missing
keys and values written entirely as key-value lines.
sort ¶
Sort direct child keys in place, keeping comments and formatting.
Accepts keyword-only key and reverse, like list.sort.
Key-value lines stay before section and array-of-tables headers
so they still belong to the same table. Keys are sorted in groups:
those with only key-value lines, those with both lines and headers,
then those with only headers. key and reverse apply within
each group.
format ¶
Canonicalise this container's formatting in place.
Normalizes spacing, indentation, and blank lines in this table and its children. Comments are retained, and multi-line values stay multi-line. Newlines use the document's line endings.
Use FormatOptions(normalize_comments=False) to leave comment
text untouched.
Add a newly created table to a document before formatting it.
For inline tables defined by dotted keys, format the enclosing
inline table, not an inner table such as a in {a.b = 1}.
Unsupported tables raise TOMLError.
Array ¶
An inline TOML array.
Array is a list subclass, so isinstance(arr, list) holds and
it can be passed wherever a list or Sequence is expected.
__init__ ¶
Construct a standalone inline array.
Array([1, 2, 3]) builds an inline array; multiline=True
lays items out one per line, indented by indent spaces.
set_multiline ¶
Switch this array between single-line and multi-line form.
When laying out multi-line, items are indented by indent
spaces and the closing bracket lines up with the row the array
starts on.
Raises TOMLError when collapsing a multi-line array that
carries comments anywhere in it, including inside nested values,
since they would have nowhere to live on one line.
Returns self for chaining.
leading_comments
property
¶
Comment lines immediately above each item, keyed by item index.
leading_block
property
¶
Comments and blank lines above each item, keyed by item index.
Comment lines are strings and blank lines are None.
format ¶
Canonicalise this array's formatting in place.
Rewrites whitespace, indentation, separators, and newlines while retaining comments and keeping multi-line values multi-line. A multi-line array's closing bracket lines up with the row the array starts on.
Use FormatOptions(normalize_comments=False) to leave comment
text untouched.
AoT ¶
An array of tables, written as repeated headers such as [[products]].
AoT is a list[Table] subclass, so isinstance(aot, list) holds
and it can be passed wherever a list or Sequence is expected.
Type aliases¶
TomlInput
module-attribute
¶
TomlInput: TypeAlias = str | int | float | bool | datetime | date | time | Array | AoT | Table | Mapping[str, Any] | list[Any]
Values accepted by mutators and factories.
Includes Table, Array,
AoT, any TOML scalar (str, int, float, bool,
datetime, date, time), and plain Mapping[str, Any] /
list[Any].
The nested list / Mapping arms intentionally use Any for
elements: tightening to a recursive alias would trip over Python's
invariant container generics (a list[int] is not assignable to
list[TomlInput]). Invalid elements are rejected at runtime when
the value is assigned.
Errors¶
TOMLError ¶
Base class for all tomlrt errors.
TOMLParseError ¶
Raised when a TOML document cannot be parsed.
The human-readable problem description is available via
str(exc) (or exc.args[0]) and has the form
"{message} (line L, column C)".
Attributes:
| Name | Type | Description |
|---|---|---|
line |
int
|
1-based line number where the error was detected. |
col |
int
|
1-based column number where the error was detected. |
offset |
int
|
0-based character offset into the source string. |