Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

msgspec-toon

msgspec-toon is a native TOON 4.1 codec for Python. It decodes TOON text directly into msgspec.Struct objects. It does not build an intermediate dict and list tree.

Use it when tabular data must fit in a language model context window, but the application still needs typed Python objects and fast in-process conversion.

This is a beta release. The project passes the pinned TOON 4.1.1 corpus, but it does not yet support every type that msgspec.json supports.

Install

Install the public beta from PyPI:

uv add msgspec-toon

The package requires Python 3.13 or newer. Its only runtime dependency is the exact pin msgspec==0.21.1. Benchmark codecs and tokenizers are optional development dependencies. They are not installed with the library.

Decode TOON into a Struct

import msgspec
import msgspec_toon as toon


class Metadata(msgspec.Struct, frozen=True):
    alias: str
    region: str


class Worker(msgspec.Struct, frozen=True):
    pid: int
    provider: str
    metadata: Metadata


class Document(msgspec.Struct, frozen=True):
    workers: list[Worker]


wire = b"""workers[2]{pid,provider,metadata{alias,region}}:
  9007199254740993,claude,worker-a,west
  80916,claude,worker-b,east"""

decoder = toon.Decoder(Document)
document = decoder.decode(wire)

assert isinstance(document, Document)
assert document.workers[0].pid == 9007199254740993
assert toon.encode(document) == wire

The parser uses the target type while it reads the input. It constructs the final Struct objects directly. The G2 allocation proof records zero temporary built-in dictionaries and lists for this path.

Read and write TOON files

The codec accepts bytes, bytearray, memoryview, or str. Encoding returns bytes, so normal Python file APIs work without an adapter.

from pathlib import Path

import msgspec_toon as toon


source = Path("workers.toon")
target = Path("workers-copy.toon")

decoder = toon.Decoder(Document)
encoder = toon.Encoder()

value = decoder.decode(source.read_bytes())
target.write_bytes(encoder.encode(value))

The conversion itself does not open files, sockets, or subprocesses. Your application controls all I/O.

Use untyped values

Omit type when you need normal Python dictionaries and lists:

value = toon.decode(b"name: ada\nactive: true")
wire = toon.encode(value)

The public surface follows msgspec.json where support exists:

  • encode and decode
  • reusable Encoder and Decoder
  • enc_hook and dec_hook
  • strict decoding by default
  • msgspec-compatible encode, decode, and validation errors

TOON wire options are explicit:

toon.encode(value, delimiter="\t", indent=1)
toon.decode(wire, indent_size=1)

Why not wrap another TOON codec?

A wrapper must first convert a Struct into built-in containers. Typed decode must parse a built-in tree and then call msgspec.convert. Those extra trees can cost more than the codec work.

Project Format target Typed msgspec path Integration model
msgspec-toon TOON 4.1.1 corpus Direct Struct encode and decode Native, in process
toon-rust TOON 3.0 No Python msgspec path Rust library and CLI
toons 0.7.0 Earlier TOON grammar Built-in tree Python Rust extension
python-toon 0.1.3 Earlier TOON grammar to_builtins / convert Pure Python and CLI

TOON 4 nested field groups are important. They let a uniform nested record use one tabular header:

workers[2]{pid,provider,metadata{alias,region}}:
  20324,claude,worker-a,west
  80916,claude,worker-b,east

Older encoders can fall back to a larger entry form for the same data.

Tokens and speed

Codec elapsed times

Absolute token counts

The generated benchmark report publishes both axes:

  • Direct encode, decode, and total time for each measured codec.
  • Absolute token counts, including compact JSON, under tiktoken o200k_base.

The report crosses four payload shapes with four record counts. Canonical TOON uses more tokens than compact JSON for the measured irregular shapes.

All timing rows come from one session and one release build. The estimator is the mean across ten independent worker processes. It never reports the minimum. The raw evidence is in conformance/report.json.

Conformance and safety

  • All 538 pinned TOON 4.1.1 fixtures pass in both directions.
  • Typed decode creates no intermediate built-in container tree.
  • Integers keep Python precision and do not route through float.
  • Errors contain coordinates and static messages, never input payload text.
  • Malformed input must return an error. It must not panic or terminate Python.
  • Canonical output is byte-locked by tests.

The generated support matrix in conformance/report.json lists supported, rejected, and not-yet-supported msgspec features. Unsupported behavior fails clearly. It does not silently return a different value.

Optional msgspec Struct fast path

The stock package reads Struct fields through msgspec's public Python attributes. This is the compatible path for msgspec==0.21.1.

The repository also contains a versioned Struct-access capsule proposal for msgspec. You can build the same codec against that patch in an isolated environment:

make fastpath-build
make fastpath-check
make fastpath-bench
.venv-fastpath/bin/python

This workflow fetches a hash-pinned msgspec commit, applies the preserved patch, and builds both release wheels. It does not modify the normal .venv. The build fails unless the capsule path is active. Published wheels do not depend on the unreleased API.

Develop and reproduce

Use uv for all Python environment work:

uv sync --locked                         # library and developer tools
make build                              # release extension in .venv
make check                              # Rust and Python checks
uv run python conformance/run.py        # pinned 538-fixture corpus
make g2                                 # allocation proof in a separate build

uv sync --group bench --locked           # opt in to benchmark packages
make bench                              # same-run codec and typed ladders
make public-report                      # raw JSON, R charts, and BENCHMARKS.md

make public-report uses the host Rscript, ggplot2, jsonlite, and scales. It does not install R or add R packages to the Python environment.

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

msgspec_toon-0.1.0b1.tar.gz (57.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

msgspec_toon-0.1.0b1-cp313-abi3-macosx_11_0_arm64.whl (323.3 kB view details)

Uploaded CPython 3.13+macOS 11.0+ ARM64

File details

Details for the file msgspec_toon-0.1.0b1.tar.gz.

File metadata

  • Download URL: msgspec_toon-0.1.0b1.tar.gz
  • Upload date:
  • Size: 57.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.2 {"installer":{"name":"uv","version":"0.12.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for msgspec_toon-0.1.0b1.tar.gz
Algorithm Hash digest
SHA256 59e79ed106b1df1d5da0b1c0fe835a48549a29a2ff5772efdea3a01cf6d3e7fa
MD5 1430d796183251c5b3e840e0dea9d311
BLAKE2b-256 5eafbbafc058882dabd5c57cdb45d0e6b7939aa1e49bdec0737fdb1a48099a4a

See more details on using hashes here.

File details

Details for the file msgspec_toon-0.1.0b1-cp313-abi3-macosx_11_0_arm64.whl.

File metadata

  • Download URL: msgspec_toon-0.1.0b1-cp313-abi3-macosx_11_0_arm64.whl
  • Upload date:
  • Size: 323.3 kB
  • Tags: CPython 3.13+, macOS 11.0+ ARM64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.2 {"installer":{"name":"uv","version":"0.12.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for msgspec_toon-0.1.0b1-cp313-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 5f2ece2ba532b874d9234b4b193a4df8fe420d5339f394f12e2e522b5ae2c81b
MD5 134901aa738d1f91e1a59dc2d5ab66d8
BLAKE2b-256 bf06cb3f148aa1e43313b6bce06d2c29b9dc5161fca393bfd029f6c1272af333

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page