dom-toml
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
- breaking In version 2.0.0, the `encoder` and `decoder` parameters for `dump`, `dumps`, `load`, and `loads` functions must now be instances or types of `dom_toml.encoder.TomlEncoder` or `dom_toml.decoder.TomlDecoder` respectively. Passing arbitrary callables is no longer supported directly.
- gotcha When using `dom_toml.load()` with a file object, it is generally recommended to open the file in binary read mode (`'rb'`). This ensures correct handling of UTF-8 encoding and universal newlines, which is in line with the TOML specification.
- gotcha Unlike Python's built-in `tomllib` (Python 3.11+) or the `tomli` library, `dom-toml` is a separate implementation that provides both reading and writing capabilities. It does not use `tomli` or `tomllib` internally, meaning its behavior and features might differ slightly.
- gotcha While TOML supports nested structures, excessively deep nesting or complex arrays of tables can become difficult to read and maintain. This is a general characteristic of the TOML format, not specific to `dom-toml`.
Install
-
pip install dom-toml -
pip install dom-toml[config]
Imports
- load
from dom_toml import load
- loads
from dom_toml import loads
- dump
from dom_toml import dump
- dumps
from dom_toml import dumps
- Config
from dom_toml.config import Config
Quickstart
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)