On this page
  1. tomllib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Loading a pyproject.toml File in Binary Mode
  7. 2. Preserving Exact Decimal Precision with parse_float
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

tomllib

Prev: tokenize | Up: stdlib_module | Next: trace
Rel: csv, configparser, netrc, plistlib
Ref: docs.python.org — tomllib
Tags: #public #python3 #stdlib


Import

import tomllib

Overview

Read-only TOML 1.0 parser built into Python 3.11+ (loads() for strings, load() for binary files). Reach for tomllib to parse pyproject.toml and application config files with zero dependencies; it is strictly read-only (no TOML writer is included in the stdlib).

Quick Start

import tomllib

raw = '''
[project]
name = "demo"
version = "0.1.0"
tags = ["python", "toml"]
'''
data = tomllib.loads(raw)
assert data["project"]["name"] == "demo"
assert data["project"]["tags"] == ["python", "toml"]

Implementation Walkthrough

1. Loading a pyproject.toml File in Binary Mode

tomllib.load() requires a binary file handle ("rb") because the TOML 1.0 specification mandates UTF-8 decoding:

import tomllib
from pathlib import Path

def read_toml(path: Path) -> dict[str, object]:
    try:
        with path.open("rb") as fh:
            return tomllib.load(fh)
    except tomllib.TOMLDecodeError as exc:
        raise ValueError(f"Invalid TOML in {path}: {exc}") from exc

2. Preserving Exact Decimal Precision with parse_float

from decimal import Decimal
import tomllib

cfg = tomllib.loads("rate = 0.075\n", parse_float=Decimal)
assert cfg["rate"] == Decimal("0.075")

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes