or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-tomli-w

A lil' TOML writer

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/tomli-w@1.2.x

To install, run

npx @tessl/cli install tessl/pypi-tomli-w@1.2.0

index.mddocs/

Tomli-W

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

Package Information

  • Package Name: tomli-w
  • Language: Python
  • Installation: pip install tomli-w
  • Requirements: Python >=3.9

Core Imports

import tomli_w

Import specific functions:

from tomli_w import dumps, dump

Basic Usage

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

Custom Indentation

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",
# ]

Multi-line Strings

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

Capabilities

String Serialization

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

File Writing

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

Package Metadata

__version__ = "1.2.0"
__all__ = ("dumps", "dump")

Supported Data Types

The library supports the following Python types for TOML serialization:

Basic Types

  • str - TOML strings (basic strings with escaping)
  • int - TOML integers
  • float - TOML floats
  • bool - TOML booleans (Truetrue, Falsefalse)

Numeric Types

  • decimal.Decimal - TOML floats with proper precision handling
    • Decimal("inf")inf
    • Decimal("-inf")-inf
    • Decimal("nan")nan

Date/Time Types

  • datetime.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)

Container Types

  • list - TOML arrays (with customizable indentation)
  • tuple - TOML arrays (treated same as list)
  • dict and other Mapping types - TOML tables or inline tables

Type Constraints and Behavior

  • Time objects with timezone: Will raise ValueError
  • Unsupported types: Will raise TypeError
  • Invalid mapping keys: Non-string keys will raise TypeError
  • Array formatting: Arrays are formatted with trailing commas and customizable indentation
  • Inline tables: Small mappings may be formatted as inline tables based on length heuristics
  • String escaping: Automatic escaping of special characters in strings
  • Order preservation: Dictionary insertion order is preserved in output

Configuration Options

multiline_strings Parameter

Controls how strings containing newlines are formatted:

  • False (default): Preserves exact newline byte sequences using escape sequences
  • True: 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
# """

indent Parameter

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", 
# ]

Error Handling

The library raises specific exceptions for error conditions:

ValueError

  • Negative indent values: ValueError("Indent width must be non-negative")
  • Time objects with timezone info: ValueError("TOML does not support offset times")

TypeError

  • Unsupported data types: TypeError("Object of type 'X' is not TOML serializable")
  • Invalid mapping keys: TypeError("Invalid mapping key 'X' of type 'Y'. A string is required.")

TOML Compliance and Limitations

  • TOML v1.0.0 compatible: Produces valid TOML output for supported input types
  • No comments support: Cannot write TOML comments (TOML comments are read-only)
  • No document sorting: Respects input dictionary order, does not sort keys
  • Output validation: No guarantee of validity for edge cases with custom types
  • Lossless round-trips: Default string handling preserves exact byte sequences
  • Bare key optimization: Simple keys are written without quotes when possible

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