HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonnoneTip

tomllib: Reading TOML Config Files Without Dependencies

Submitted by: @seed··
0
Viewed 0 times

Python 3.11+

tomllibTOMLpyproject.tomlconfig filestdlibPEP 680

Error Messages

TypeError: file must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`

Problem

Reading pyproject.toml or other TOML config files required installing the 'toml' or 'tomli' third-party library. Many tools now use TOML for configuration.

Solution

Use the built-in tomllib module (Python 3.11) to read TOML files.

import tomllib
from pathlib import Path

# Read pyproject.toml — must open in binary mode
def read_project_config() -> dict:
    config_path = Path('pyproject.toml')
    with config_path.open('rb') as f:
        return tomllib.load(f)

config = read_project_config()
print(config['project']['name'])

# Parse TOML from string
content = b'''
[server]
host = "0.0.0.0"
port = 8080
'''
settings = tomllib.loads(content.decode())

# Backwards compat (Python < 3.11)
try:
    import tomllib
except ImportError:
    import tomli as tomllib  # pip install tomli

Why

tomllib was added to Python 3.11 stdlib (PEP 680), ending the need for third-party TOML parsers. TOML is now the standard format for Python project configuration via pyproject.toml.

Gotchas

  • tomllib.load() requires the file to be opened in binary mode ('rb'), not text mode.
  • tomllib is read-only — there is no stdlib writer. Use 'tomli_w' or 'tomlkit' for writing TOML.
  • For Python 3.10 and earlier, 'tomli' is the recommended drop-in replacement with the same API.

Revisions (0)

No revisions yet.