brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's tomllib reads TOML config files without installing anything

Python
~/tips/tip-python-tomllib-read-config

import tomllib

Reads a TOML file such as pyproject.toml with the standard library, no extra package.

If your script reads a TOML config and you still install a package for it, you can drop that dependency. Since Python 3.11 the standard library has tomllib.

import tomllib

with open("pyproject.toml", "rb") as f:
    data = tomllib.load(f)

print(data["project"]["name"])

You get a normal dict back. Tables become nested dicts, arrays become lists, and dates come back as datetime objects.

Note the "rb". tomllib.load() wants a file opened in binary mode, and passing a text file gives you an error. If you already have the text in a string, use tomllib.loads() instead.

Bad TOML raises tomllib.TOMLDecodeError, which is a ValueError, so you can catch it and print a friendly message about which config file is broken.

There is one option worth knowing: parse_float. Pass parse_float=decimal.Decimal and prices or other exact numbers do not turn into floats with rounding surprises.

Caveat: it only reads. The docs say plainly that the module does not support writing TOML and point to tomli-w for that, or tomlkit if you want to keep comments and layout. And it is 3.11 and newer only, so check your server’s Python version before you ship it there. The docs also say to be careful with TOML from untrusted sources.

Further reading: Python docs: tomllib

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link