API reference¶
The complete public surface, generated from the docstrings in the source.
Stability¶
Anything imported from the top-level tomlrt namespace is part of the public,
semver-stable API:
| Symbol | Kind |
|---|---|
loads, load |
function |
dumps, dump |
function |
Document, Table, Array, AoT |
class |
FormatOptions |
class |
TomlInput |
type alias |
TOMLError, TOMLParseError |
exception |
Anything not re-exported from tomlrt/__init__.py (modules prefixed with _,
internal helpers) may change without notice and should not be imported by user
code.
Top-level functions¶
load ¶
load(fp: IO[bytes]) -> Document
Parse a TOML document from a binary file-like object.
The file must be opened in binary mode (open(path, "rb")).
dumps ¶
dumps(data: Mapping[str, Any]) -> str
dump ¶
dump(data: Mapping[str, Any], fp: IO[bytes]) -> None
Formatting¶
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.
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__ ¶
__init__(data: Mapping[str, Any] | None = None) -> None
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.
Constructing copies. Every value in data is copied into the
new document, so later mutations through your own references
are not visible in it -- and a rejected data leaves them all
alone. A Table / Array /
AoT contributes its contents and its shape
(section or inline, array or array-of-tables). Available comments
and spacing are preserved, including on entries of lists and
standalone arrays-of-tables.
To have the document keep your object, assign it instead:
doc[k] = table attaches live. See
Editing documents.
render ¶
render() -> str
Serialize the document back to a TOML string.
Equivalent to tomlrt.dumps(self).
table ¶
table(key: str | Sequence[str]) -> 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 ¶
aot(key: str | Sequence[str]) -> AoT
Return the value at key typed as an array-of-tables (AoT).
entry ¶
entry(key: str | Sequence[str]) -> Any
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_table ¶
get_table(key: str | Sequence[str]) -> Table | None
get_table(key: str | Sequence[str], default: _T) -> Table | _T
get_table(key: str | Sequence[str], default: object = None) -> object
Like table(key) but returns default if the key is missing.
get_array ¶
get_array(key: str | Sequence[str]) -> Array | None
get_array(key: str | Sequence[str], default: _T) -> Array | _T
get_array(key: str | Sequence[str], default: object = None) -> object
Like array(key) but returns default if the key is missing.
get_aot ¶
get_aot(key: str | Sequence[str]) -> AoT | None
get_aot(key: str | Sequence[str], default: _T) -> AoT | _T
get_aot(key: str | Sequence[str], default: object = None) -> object
Like aot(key) but returns default if the key is missing.
get_entry ¶
get_entry(key: str | Sequence[str], default: Any = None) -> Any
Like entry(key) but returns default if the path is missing.
install ¶
install(path: str | Sequence[str], value: TomlInput) -> Any
Set value at the (possibly dotted) path.
Existing parents retain their form for scalar and inline values.
Installing a section-style container or AoT from an attached section
or document promotes inline ancestors as needed. An inline receiver
or detached inline ancestor cannot be promoted this way.
Returns the stored value or live view. Rejected paths and values leave the document unchanged.
ensure_table ¶
ensure_table(key: str | Sequence[str], *, promote_inline: bool | None = None) -> Table
Return the table at key, creating it if missing.
Existing section and inline tables are traversed without changing
their representation. A missing child of an inline table is created
inline; elsewhere, missing intermediate components stay implicit and
only the deepest component gets an explicit [a.b.c] header.
Raises TOMLError if an existing component is an array-of-tables or
non-table value.
promote_inline is deprecated and ignored. Use promote_inline()
to request conversion explicitly.
promote_inline ¶
promote_inline(key: str) -> Table
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 ¶
promote_array(key: str) -> AoT
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
¶
preamble: tuple[str, ...]
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
¶
epilogue: tuple[str | None, ...]
Comment block at the very end of the document.
The trailing comments that follow all structural content, as bare
comment texts (without the leading #) with None for each
blank line, in source order. With no structural content everything
is preamble instead.
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 structural content.
comments
property
¶
comments: MutableMapping[str, str]
Mapping view of EOL comments on this container's direct keys.
Comments may be set before attachment. Section tables expose direct key/value entries; inline tables expose direct leaf entries. Adding comments to a single-line inline table makes it multi-line.
leading_comments
property
¶
leading_comments: MutableMapping[str, tuple[str, ...]]
Mapping view of leading-comment blocks on this container's direct keys.
Returns only the attached comment run immediately above each key
(no blank line between). For the full block, including any
above-blank groups and the blank-line structure between them, see
leading_block.
Comments may be set before attachment. Inline tables expose direct leaf entries with the same attached-run semantics. Adding comments makes a single-line inline table multi-line.
leading_block
property
¶
leading_block: MutableMapping[str, tuple[str | None, ...]]
Mapping view of full leading-trivia blocks on direct keys.
Each entry is a tuple[str | None, ...] of comment strings
interleaved with None (one per blank line), in source order;
the slot's own column indent is implicit and re-applied on write.
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.
Blocks may be set before attachment. Inline tables expose direct leaf entries; opening-bracket EOL comments are framing and are not part of the first entry's block.
sort ¶
sort(*, key: Callable[[str], SupportsRichComparison] | None = None, reverse: bool = False) -> None
Sort direct child keys in place, preserving per-key trivia.
Mirrors list.sort: keyword-only key / reverse,
stable, in-place. Structural keys (children bound to an AoT
or to a section Table, i.e. one rendered with a [header])
are always placed after bare keys; otherwise a bare key after a
section header would re-bind under it. key and reverse
apply within, never across, the partitions. Implicit sections
built from dotted keys (e.g. a.x = 1) sort as bare keys.
Inline containers have no structural children, so the partition
is a no-op and key / reverse behave as on a plain dict.
See has_header for the predicate
that defines the partition; a custom key function can call it
to decide which side of the split a given child sits on.
format ¶
format(*, options: FormatOptions | None = None, comments: bool | None = None) -> None
Canonicalise this container's formatting in place.
Rewrites this subtree to the canonical layout:
- Keys,
=spacing, and header brackets use canonical whitespace. - Sibling key/value slots have no blank line between them; section / array-of-tables headers get one.
- Orphan comment blocks above slots are preserved, with each blank-line run collapsed to one.
- Inline values keep their shape (single-line stays single-line, multi-line stays multi-line), and a multi-line one closes on the row it starts on.
- Newlines use the owning document's style.
comments= is deprecated; use
FormatOptions(normalize_comments=...) instead. Supplying both
arguments raises ValueError.
Factory-style containers without layout yet (Table.section() /
Table.inline()) and inline dotted
navigators are unsupported and 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
¶
section(mapping: Mapping[str, TomlInput] | None = None) -> Table
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
¶
inline(mapping: Mapping[str, TomlInput] | None = None) -> Table
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
¶
multiline: bool
Whether this inline table is laid out across multiple lines.
Raises TOMLError on a non-inline table.
set_multiline ¶
set_multiline(*, multiline: bool, indent: int = 4) -> Table
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 ¶
table(key: str | Sequence[str]) -> 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 ¶
aot(key: str | Sequence[str]) -> AoT
Return the value at key typed as an array-of-tables (AoT).
entry ¶
entry(key: str | Sequence[str]) -> Any
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_table ¶
get_table(key: str | Sequence[str]) -> Table | None
get_table(key: str | Sequence[str], default: _T) -> Table | _T
get_table(key: str | Sequence[str], default: object = None) -> object
Like table(key) but returns default if the key is missing.
get_array ¶
get_array(key: str | Sequence[str]) -> Array | None
get_array(key: str | Sequence[str], default: _T) -> Array | _T
get_array(key: str | Sequence[str], default: object = None) -> object
Like array(key) but returns default if the key is missing.
get_aot ¶
get_aot(key: str | Sequence[str]) -> AoT | None
get_aot(key: str | Sequence[str], default: _T) -> AoT | _T
get_aot(key: str | Sequence[str], default: object = None) -> object
Like aot(key) but returns default if the key is missing.
get_entry ¶
get_entry(key: str | Sequence[str], default: Any = None) -> Any
Like entry(key) but returns default if the path is missing.
install ¶
install(path: str | Sequence[str], value: TomlInput) -> Any
Set value at the (possibly dotted) path.
Existing parents retain their form for scalar and inline values.
Installing a section-style container or AoT from an attached section
or document promotes inline ancestors as needed. An inline receiver
or detached inline ancestor cannot be promoted this way.
Returns the stored value or live view. Rejected paths and values leave the document unchanged.
ensure_table ¶
ensure_table(key: str | Sequence[str], *, promote_inline: bool | None = None) -> Table
Return the table at key, creating it if missing.
Existing section and inline tables are traversed without changing
their representation. A missing child of an inline table is created
inline; elsewhere, missing intermediate components stay implicit and
only the deepest component gets an explicit [a.b.c] header.
Raises TOMLError if an existing component is an array-of-tables or
non-table value.
promote_inline is deprecated and ignored. Use promote_inline()
to request conversion explicitly.
promote_inline ¶
promote_inline(key: str) -> Table
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 ¶
promote_array(key: str) -> AoT
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
¶
header_comment: str | None
The EOL comment on this container's section header, or None.
Section factories may be annotated before attachment.
Document roots and implicit sections opened only by a nested
[a.b] header read as None. Setting on such a container raises
TOMLError; inline tables also raise.
header_leading_comments
deletable
property
writable
¶
header_leading_comments: tuple[str, ...]
The attached comment block immediately above this container's header.
Section factories may be annotated before attachment.
Document roots and implicit sections opened only by a nested
[a.b] header read as ().
Setting on such a container raises TOMLError;
inline tables also raise.
Excludes any above-blank groups — those are visible via
header_leading_block.
header_leading_block
deletable
property
writable
¶
header_leading_block: tuple[str | None, ...]
The full leading-trivia block above this container's header.
A tuple[str | None, ...] of comment strings interleaved with
None (one per blank line), in source order. Section factories
may be annotated before attachment. Document roots and implicit
sections opened only by a nested [a.b] header read as ().
Setting on such a container raises TOMLError;
inline tables also raise.
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
¶
comments: MutableMapping[str, str]
Mapping view of EOL comments on this container's direct keys.
Comments may be set before attachment. Section tables expose direct key/value entries; inline tables expose direct leaf entries. Adding comments to a single-line inline table makes it multi-line.
leading_comments
property
¶
leading_comments: MutableMapping[str, tuple[str, ...]]
Mapping view of leading-comment blocks on this container's direct keys.
Returns only the attached comment run immediately above each key
(no blank line between). For the full block, including any
above-blank groups and the blank-line structure between them, see
leading_block.
Comments may be set before attachment. Inline tables expose direct leaf entries with the same attached-run semantics. Adding comments makes a single-line inline table multi-line.
leading_block
property
¶
leading_block: MutableMapping[str, tuple[str | None, ...]]
Mapping view of full leading-trivia blocks on direct keys.
Each entry is a tuple[str | None, ...] of comment strings
interleaved with None (one per blank line), in source order;
the slot's own column indent is implicit and re-applied on write.
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.
Blocks may be set before attachment. Inline tables expose direct leaf entries; opening-bracket EOL comments are framing and are not part of the first entry's block.
has_header ¶
has_header(key: str) -> bool
Whether key's rendered block contains a structural header.
This describes the whole block, not the child table itself: with
[a.b], doc.has_header("a") is true although a is implicit
and only b owns the header. Structural headers are [header]
sections and [[header]] array-of-tables entries. Returns False
for bare key = value leaves, inline tables, implicit sections built
entirely from dotted keys (e.g. a.x = 1), and missing keys.
sort ¶
sort(*, key: Callable[[str], SupportsRichComparison] | None = None, reverse: bool = False) -> None
Sort direct child keys in place, preserving per-key trivia.
Mirrors list.sort: keyword-only key / reverse,
stable, in-place. Structural keys (children bound to an AoT
or to a section Table, i.e. one rendered with a [header])
are always placed after bare keys; otherwise a bare key after a
section header would re-bind under it. key and reverse
apply within, never across, the partitions. Implicit sections
built from dotted keys (e.g. a.x = 1) sort as bare keys.
Inline containers have no structural children, so the partition
is a no-op and key / reverse behave as on a plain dict.
See has_header for the predicate
that defines the partition; a custom key function can call it
to decide which side of the split a given child sits on.
format ¶
format(*, options: FormatOptions | None = None, comments: bool | None = None) -> None
Canonicalise this container's formatting in place.
Rewrites this subtree to the canonical layout:
- Keys,
=spacing, and header brackets use canonical whitespace. - Sibling key/value slots have no blank line between them; section / array-of-tables headers get one.
- Orphan comment blocks above slots are preserved, with each blank-line run collapsed to one.
- Inline values keep their shape (single-line stays single-line, multi-line stays multi-line), and a multi-line one closes on the row it starts on.
- Newlines use the owning document's style.
comments= is deprecated; use
FormatOptions(normalize_comments=...) instead. Supplying both
arguments raises ValueError.
Factory-style containers without layout yet (Table.section() /
Table.inline()) and inline dotted
navigators are unsupported and 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__ ¶
__init__(items: Iterable[TomlInput] = (), *, multiline: bool = False, indent: int = 4) -> None
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 ¶
set_multiline(*, multiline: bool, indent: int = 4) -> Array
Switch this array between flush 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.
get_table ¶
get_table(index: SupportsIndex) -> Table | None
get_table(index: SupportsIndex, default: _T) -> Table | _T
get_table(index: SupportsIndex, default: object = None) -> object
Like table(index) but returns default for out-of-range.
get_array ¶
get_array(index: SupportsIndex) -> Array | None
get_array(index: SupportsIndex, default: _T) -> Array | _T
get_array(index: SupportsIndex, default: object = None) -> object
Like array(index) but returns default for out-of-range.
leading_comments
property
¶
leading_comments: MutableMapping[int, tuple[str, ...]]
Attached leading-comment view, indexed by item position.
leading_block
property
¶
leading_block: MutableMapping[int, tuple[str | None, ...]]
Full leading-block view, indexed by item position.
Comment lines are strings and blank lines are None.
format ¶
format(*, options: FormatOptions | None = None, comments: bool | None = None) -> None
Canonicalise this array's formatting in place.
Rewrites whitespace, indentation, separators, and newlines while preserving shape (single-line stays single-line, multi-line stays multi-line) and orphan comment text. A multi-line array's closing bracket lines up with the row the array starts on.
comments= is deprecated; use
FormatOptions(normalize_comments=...) instead. Supplying both
arguments raises ValueError.
AoT ¶
An Array-of-tables, e.g. [[products]] repeated.
AoT is a list[Table] subclass, so isinstance(aot, list) holds
and it can be passed wherever a list or Sequence is expected.
__init__ ¶
__init__(entries: Iterable[Mapping[str, TomlInput]] = ()) -> None
Construct a standalone array-of-tables.
add ¶
add(entry: Mapping[str, TomlInput] | None = None) -> Table
Append a fresh [[path]] entry and return its Table view.
entry may be initial body content or None. Attached AoTs
append to the owning document.
to_list ¶
to_list() -> list[dict[str, Any]]
Materialise independent plain-Python dictionaries (recursive).
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. |