Skip to content

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

loads

loads(text: str) -> Document

Parse a TOML document string into a Document.

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

Serialize a document or mapping to a TOML string.

Plain mappings are written using the same rules as Document(data).

dump

dump(data: Mapping[str, Any], fp: IO[bytes]) -> None

Serialize a Document and write it to a binary stream.

The file must be opened in binary mode (open(path, "wb")).

Accepts a plain mapping as well as a Document (see dumps).

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.

normalize_comments instance-attribute

normalize_comments = normalize_comments

indent instance-attribute

indent = indent

eol_comment_spaces instance-attribute

eol_comment_spaces = eol_comment_spaces

multiline_trailing_comma instance-attribute

multiline_trailing_comma = multiline_trailing_comma

quote_style instance-attribute

quote_style = quote_style

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.

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

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.

array

array(key: str | Sequence[str]) -> Array

Return the value at key typed as an Array.

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.

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

ensure_table(key: str | Sequence[str], *, promote_inline: bool | None = None) -> 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

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.

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

comments: MutableMapping[str, str]

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

leading_comments: MutableMapping[str, tuple[str, ...]]

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

leading_block: MutableMapping[str, tuple[str | None, ...]]

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(*, key: Callable[[str], SupportsRichComparison] | None = None, reverse: bool = False) -> None

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

format(*, options: FormatOptions | None = None) -> None

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.

to_dict

to_dict() -> dict[str, Any]

Return a deep copy as a plain Python dictionary.

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})

is_inline property

is_inline: bool

True for inline {...} tables, False for [section] blocks.

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.

array

array(key: str | Sequence[str]) -> Array

Return the value at key typed as an Array.

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.

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

ensure_table(key: str | Sequence[str], *, promote_inline: bool | None = None) -> 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

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 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

header_leading_comments: tuple[str, ...]

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

header_leading_block: tuple[str | None, ...]

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

comments: MutableMapping[str, str]

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

leading_comments: MutableMapping[str, tuple[str, ...]]

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

leading_block: MutableMapping[str, tuple[str | None, ...]]

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

has_header(key: str) -> bool

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(*, key: Callable[[str], SupportsRichComparison] | None = None, reverse: bool = False) -> None

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

format(*, options: FormatOptions | None = None) -> None

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.

to_dict

to_dict() -> dict[str, Any]

Return a deep copy as a plain Python dictionary.

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.

multiline property writable

multiline: bool

Whether this array is written across multiple lines.

set_multiline

set_multiline(*, multiline: bool, indent: int = 4) -> Array

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.

table

table(index: SupportsIndex) -> Table

Return self[index] typed as a Table.

array

array(index: SupportsIndex) -> Array

Return self[index] typed as a nested Array.

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.

comments property

comments: MutableMapping[int, str]

End-of-line comments, keyed by item index.

leading_comments property

leading_comments: MutableMapping[int, tuple[str, ...]]

Comment lines immediately above each item, keyed by item index.

leading_block property

leading_block: MutableMapping[int, tuple[str | None, ...]]

Comments and blank lines above each item, keyed by item index.

Comment lines are strings and blank lines are None.

format

format(*, options: FormatOptions | None = None) -> None

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.

to_list

to_list() -> list[Any]

Return a deep copy as a plain Python list.

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.

__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 table and return it.

entry supplies the table's initial values; None creates an empty table.

to_list

to_list() -> list[dict[str, Any]]

Return a deep copy as a list of plain Python dictionaries.

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.

line instance-attribute

line: int = line

col instance-attribute

col: int = col

offset instance-attribute

offset: int = offset