Registry / serialization / tomli-w

tomli-w

JSON →
library1.2.0pypypi✓ verified 26d ago

Tomli-W is a pure Python library designed for writing TOML (Tom's Obvious, Minimal Language) documents. It acts as the write-only counterpart to the `tomli` parser (which is also the basis for the `tomllib` standard library module in Python 3.11+). It is fully compatible with TOML v1.0.0 and focuses on simplicity and correctness in output. The library maintains an active status with periodic updates.

pip install tomli-w
INSTALL
IMPORT
SIG · TOMLI-W
T
tomli-w
serializationpythonv1.2.0
Install
1.8s avg
Import
10ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.002s · 17.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.8s · import 0.002s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

tomli_w
import tomli_w
Provides `dump()` for writing to files and `dumps()` for writing to strings.

This example demonstrates how to write a Python dictionary to a TOML formatted string using `tomli_w.dumps()` and how to write it directly to a file using `tomli_w.dump()`. It includes a cleanup step to remove the generated file.

import tomli_w import os # Example data to write doc = { "title": "My Awesome Project", "owner": { "name": "Alice Example", "organization": "Example Corp", "dob": "1979-05-27T07:32:00-08:00" }, "database": { "server": "192.168.1.1", "ports": [8001, 8001, 8002], "connection_max": 5000, "enabled": True }, "servers": { "alpha": { "ip": "10.0.0.1", "dc": "eqdc10" }, "beta": { "ip": "10.0.0.2", "dc": "eqdc10" } } } # 1. Write to a string toml_string = tomli_w.dumps(doc) print("--- TOML String ---") print(toml_string) # 2. Write to a file file_path = "config.toml" try: with open(file_path, "wb") as f: tomli_w.dump(doc, f) print(f"\n--- TOML written to {file_path} ---") with open(file_path, "r") as f_read: print(f_read.read()) except Exception as e: print(f"Error writing TOML to file: {e}") finally: if os.path.exists(file_path): os.remove(file_path) # Clean up
Debug
Known issues
breaking`tomli-w` requires Python 3.9 or newer. Attempts to use it on older Python versions will result in an `ImportError` or `SyntaxError`.
fix
Ensure your Python environment is 3.9 or newer. Consider `tomllib` (Python 3.11+) or `tomlkit` for broader compatibility needs if you need a writer for older Python versions.
affects: <1.0.0 (older versions of `tomli`, counterpart, had Python 3.6+ support, but `tomli-w` consistently targets newer Python versions).
gotcha`tomli-w` does not preserve comments, original ordering (beyond respecting input dictionary order), or custom whitespace. For style-preserving writing (e.g., maintaining comments, specific indentation), `tomlkit` is a recommended alternative.
fix
If style preservation is critical, evaluate `tomlkit`. Otherwise, ensure your workflow does not depend on output TOML mirroring input formatting precisely.
affects: All versions
gotchaThe library does not automatically validate the generated TOML. If the input data contains non-standard types or structures that could result in invalid TOML (e.g., objects whose `__str__` method produces invalid TOML syntax), `tomli-w` will write it without raising an error. It's recommended to validate the output by parsing it with a TOML reader like `tomli.loads()` (or `tomllib.loads()` in Python 3.11+).
fix
After writing, parse the generated TOML string or file content with `tomli.loads()` within a `try-except tomli.TOMLDecodeError` block to ensure validity, especially if the input data source is untrusted or complex.
affects: All versions
gotchaWhen writing TOML to a file using `tomli_w.dump()`, the file must be opened in binary write mode (`'wb'`). Using text mode (`'w'`) can lead to encoding issues (e.g., incorrect UTF-8 handling) or incorrect newline handling.
fix
Always open files with `mode='wb'` when using `tomli_w.dump()`: `with open('config.toml', 'wb') as f: tomli_w.dump(data, f)`.
affects: All versions
gotchaBy default, `tomli-w` avoids writing multi-line strings (using triple quotes in TOML) even if the Python string value contains newlines. This design choice aims to ensure lossless parse/write round-trips for TOML strings where exact byte representation matters.
fix
Be aware that strings with newlines will be output as single-line TOML strings with escaped newline characters (e.g., `\n`). If multi-line visual representation is strictly required, manual string formatting before passing to `tomli_w` or using `tomlkit` might be necessary.
affects: All versions
gotcha`tomli-w` is exclusively for writing TOML and does not provide any functionality for parsing or reading TOML documents.
fix
For reading TOML, use the `tomli` library (for Python <3.11) or Python's built-in `tomllib` module (for Python 3.11+).
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'tomli_w'
The `tomli-w` package is not installed in the current Python environment, or the module name `tomli_w` is misspelled.
fix
Install the library using pip: `pip install tomli-w`
AttributeError: module 'tomli_w' has no attribute 'load'
`tomli-w` is a write-only library designed for creating TOML documents and does not include functions for parsing (reading) TOML files.
fix
Use the `tomli` library (or `tomllib` in Python 3.11+) to read TOML files, e.g., `import tomli` then `tomli.load(fp)`.
TypeError: Object of type set is not TOML serializable
`tomli-w` encountered a Python object type (like a `set` or custom class instance) that cannot be directly represented in the TOML specification.
fix
Ensure all values in the dictionary intended for serialization are standard TOML-compatible types (strings, integers, floats, booleans, lists, dictionaries, datetime objects). Convert unsupported types to a serializable form if necessary.
AttributeError: 'str' object has no attribute 'write'
The `tomli_w.dump()` function expects a file-like object (opened in write mode) as its second argument, not a string representing a file path.
fix
Open the file in write mode using `open()` and pass the resulting file object to `tomli_w.dump()`, for example: `with open('config.toml', 'wb') as f: tomli_w.dump(data, f)`.
Upgrade
Version history
1.2.0latest on PyPI · released Jan 15, 2025
Audit
Dependencies

No dependency data recorded yet.

Agent activity
20 hits · last 30 days
node
16
Amazon
1
OpenAI (training)
1
Resources