← retour aux snippets

tomllib: charger un fichier TOML (stdlib)

Lire un TOML avec tomllib (Python 3.11+) sans dépendance externe.

python config #tomllib#toml#config

objectif

Lire un TOML avec tomllib (Python 3.11+) sans dépendance externe.

code minimal

import tomllib  # Python 3.11+
data = tomllib.loads("title='demo'\n[server]\nport=8000\n")
print(data["server"]["port"] == 8000)  # attendu: True

utilisation

import tomllib
s = "x=1\n"
print(tomllib.loads(s)["x"] == 1)

variante(s) utile(s)

import tomllib
doc = "arr=[1,2,3]\n"
d = tomllib.loads(doc)
print(sum(d["arr"]) == 6)

notes

  • tomllib ne fait que le chargement (pas d’écriture).
  • Pour écrire, utilisez tomli-w (lib externe) ou un autre format.