Skip to content

Building documents

From scratch

from tomlrt import Document, dumps

doc = Document()
doc["title"] = "example"
print(dumps(doc))
title = "example"

From a dict

Pass a mapping to Document to populate it recursively:

from tomlrt import Document, dumps

data = {
    "project": {
        "name": "demo",
        "version": "0.1.0",
        "dependencies": ["requests>=2"],
    },
    "tool": {"ruff": {"line-length": 88}},
}

doc = Document(data)
print(dumps(doc))
[project]
name = "demo"
version = "0.1.0"
dependencies = ["requests>=2"]

[tool.ruff]
line-length = 88

Nested mappings become [section] blocks (not inline tables); lists of mappings become [[array.of.tables]] blocks; everything else is an ordinary key-value assignment.

Document(data) copies its input; changing data afterward does not affect the document.

Choosing tables and arrays

When assigning individual values, a plain dict installs as an inline table; a plain list installs as an inline array. Use Table.section() or Table.inline() to choose the table form, and AoT or Array to choose the array form:

from tomlrt import AoT, Array, Document, Table, dumps

doc = Document()
doc["tool"] = Table.section({"version": 1})
doc["xy"] = Table.inline({"x": 1, "y": 2})
doc["pkgs"] = AoT([{"a": 1}, {"b": 2}])
doc["tags"] = Array(["a", "b"], multiline=True)
print(dumps(doc))
xy = { x = 1, y = 2 }
tags = [
    "a",
    "b",
]

[tool]
version = 1

[[pkgs]]
a = 1

[[pkgs]]
b = 2