A lil' TOML writer
npx @tessl/cli install tessl/pypi-tomli-w@1.2.0A lil' TOML writer for Python that serializes Python data structures to TOML (Tom's Obvious, Minimal Language) format. It serves as a write-only counterpart to the Tomli TOML parser, providing functionality to serialize Python dictionaries and other data structures into valid TOML format. The library is fully compatible with TOML v1.0.0 specification and supports customizable indentation for array content.
pip install tomli-wimport tomli_wImport specific functions:
from tomli_w import dumps, dumpimport tomli_w
# Create a Python dictionary
doc = {"table": {"nested": {}, "val3": 3}, "val2": 2, "val1": 1}
# Convert to TOML string
toml_string = tomli_w.dumps(doc)
print(toml_string)
# Output:
# val2 = 2
# val1 = 1
#
# [table]
# val3 = 3
#
# [table.nested]
# Write to file
with open("config.toml", "wb") as f:
tomli_w.dump(doc, f)import tomli_w
doc = {"fruits": ["orange", "kiwi", "papaya"]}
# Use custom indentation for arrays
toml_string = tomli_w.dumps(doc, indent=2)
print(toml_string)
# Output:
# fruits = [
# "orange",
# "kiwi",
# "papaya",
# ]import tomli_w
doc = {"message": "Line 1\nLine 2\nLine 3"}
# Enable multi-line string literals
toml_string = tomli_w.dumps(doc, multiline_strings=True)
print(toml_string)
# Output:
# message = """
# Line 1
# Line 2
# Line 3
# """Converts Python objects to TOML formatted strings.
def dumps(
obj: Mapping[str, Any],
/,
*,
multiline_strings: bool = False,
indent: int = 4
) -> str:
"""
Serialize a Python mapping to a TOML string.
Args:
obj: The Python object to serialize (must be a mapping/dictionary)
multiline_strings: Whether to allow multi-line string literals (default: False)
indent: Indentation width for array content (default: 4, must be non-negative)
Returns:
str: TOML-formatted string
Raises:
ValueError: If indent is negative or time objects have timezone info
TypeError: If obj contains unsupported types or invalid mapping keys
"""Writes Python objects directly to TOML files.
def dump(
obj: Mapping[str, Any],
fp: IO[bytes],
/,
*,
multiline_strings: bool = False,
indent: int = 4,
) -> None:
"""
Write a Python mapping to a TOML file.
Args:
obj: The Python object to serialize (must be a mapping/dictionary)
fp: File-like object opened in binary write mode
multiline_strings: Whether to allow multi-line string literals (default: False)
indent: Indentation width for array content (default: 4, must be non-negative)
Returns:
None
Raises:
ValueError: If indent is negative or time objects have timezone info
TypeError: If obj contains unsupported types or invalid mapping keys
"""__version__ = "1.2.0"
__all__ = ("dumps", "dump")The library supports the following Python types for TOML serialization:
str - TOML strings (basic strings with escaping)int - TOML integersfloat - TOML floatsbool - TOML booleans (True → true, False → false)decimal.Decimal - TOML floats with proper precision handling
Decimal("inf") → infDecimal("-inf") → -infDecimal("nan") → nandatetime.date - TOML local dates (ISO 8601 format)datetime.datetime - TOML local datetimes (ISO 8601 format)datetime.time - TOML local times (ISO 8601 format, must not have timezone info)list - TOML arrays (with customizable indentation)tuple - TOML arrays (treated same as list)dict and other Mapping types - TOML tables or inline tablesValueErrorTypeErrorTypeErrorControls how strings containing newlines are formatted:
False (default): Preserves exact newline byte sequences using escape sequencesTrue: Uses TOML multi-line string literals (may not preserve exact newline bytes)# Default behavior (preserves newline bytes)
tomli_w.dumps({"s": "line1\r\nline2"})
# s = "line1\r\nline2"
# Multi-line strings enabled
tomli_w.dumps({"s": "line1\r\nline2"}, multiline_strings=True)
# s = """
# line1
# line2
# """Controls indentation width for array content (must be non-negative integer):
data = {"items": ["a", "b", "c"]}
# Default indent=4
tomli_w.dumps(data)
# items = [
# "a",
# "b",
# "c",
# ]
# Custom indent=2
tomli_w.dumps(data, indent=2)
# items = [
# "a",
# "b",
# "c",
# ]The library raises specific exceptions for error conditions:
ValueError("Indent width must be non-negative")ValueError("TOML does not support offset times")TypeError("Object of type 'X' is not TOML serializable")TypeError("Invalid mapping key 'X' of type 'Y'. A string is required.")For output validation, parse the result with a TOML parser like tomli:
import tomli
import tomli_w
data = {"key": "value"}
toml_string = tomli_w.dumps(data)
# Validate output
try:
tomli.loads(toml_string)
print("Valid TOML")
except tomli.TOMLDecodeError:
print("Invalid TOML")