dom-toml

2.3.0 · active · verified Wed Apr 15

dom-toml is a Python library providing tools for parsing and writing Tom's Obvious, Minimal Language (TOML) files. It offers functionalities for both loading TOML data from strings or files into Python dictionaries and dumping Python data structures back into TOML format. The library is actively maintained, with frequent releases addressing features and compatibility, and the current version is 2.3.0.

Warnings

Install

Imports

Quickstart

Demonstrates loading TOML from a string, modifying the resulting dictionary, and then dumping it back to a TOML string and writing it to a file. This covers the core read/write functionality.

import os
from dom_toml import loads, dumps

# Example TOML string
toml_data_str = """
[project]
name = "my-package"
version = "0.1.0"
authors = [
    { name = "Alice", email = "alice@example.com" },
    { name = "Bob", email = "bob@example.com" }
]
"""

# Load TOML from a string
config = loads(toml_data_str)
print("Loaded TOML:", config)
# Expected: {'project': {'name': 'my-package', 'version': '0.1.0', 'authors': [{'name': 'Alice', 'email': 'alice@example.com'}, {'name': 'Bob', 'email': 'bob@example.com'}]}}

# Modify data (optional)
config['project']['license'] = 'MIT'

# Dump Python dict to TOML string
updated_toml_str = dumps(config)
print("\nUpdated TOML string:\n", updated_toml_str)

# Example of writing to a file (requires a temporary file)
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.toml') as tmp_file:
    tmp_file_name = tmp_file.name
    dump(config, tmp_file_name)

print(f"\nTOML written to {tmp_file_name}. Contents:\n")
with open(tmp_file_name, 'r') as f:
    print(f.read())

# Clean up temporary file
os.remove(tmp_file_name)

view raw JSON →