TOML
官方文档: https://docs.python.org/zh-cn/3.12/library/tomllib.html
TOML(Tom’s Obvious Minimal Language) 是一种结构清晰、非常适合作为配置文件的格式,类似 INI,但语法更严格,支持更多数据类型。
被广泛用于:
- pyproject.toml
- Poetry
- Black
- Ruff
- FastAPI 配置
- 开发环境变量
Python 没有内置 TOML,需要安装库:
安装推荐库:tomli(读)或 tomllib(Python 3.11+ 内置)
- Python 3.11+:推荐使用内置 tomllib
- Python 3.10-:推荐使用非常轻量的 tomli
Python 3.11+:
import tomllib
with open("config.toml", "rb") as f:
data = tomllib.load(f)
Python 3.10 或更低:
pip install tomli
import tomli
with open("config.toml", "rb") as f:
data = tomli.load(f)
推荐:
pip install tomli-w
示例:
import tomli_w
data = {
"server": {"host": "127.0.0.1", "port": 8080},
"debug": True,
}
with open("config.toml", "wb") as f:
tomli_w.dump(data, f)
输出:
[server]
host = "127.0.0.1"
port = 8080
debug = true
title = "config system"
port = 8080
enabled = true
[database]
host = "localhost"
port = 3306
[server.api]
url = "/v1"
timeout = 10
等同于 Python:
{"server": {"api": {"url": "/v1", "timeout": 10}}}
ports = [8001, 8002, 8003]
[[plugins]]
name = "redis"
enabled = true
[[plugins]]
name = "mysql"
enabled = false
等于 Python:
{
"plugins": [
{"name": "redis", "enabled": True},
{"name": "mysql", "enabled": False},
]
}
time = 2025-02-20T08:00:00Z
Python 读取 -> datetime 对象。
config.toml:
[server]
host = "127.0.0.1"
port = 8080
[auth]
token = "abcd1234"
expires = 30
Python 读取:
import tomllib
with open("config.toml", "rb") as f:
cfg = tomllib.load(f)
print(cfg["server"]["host"])
print(cfg["auth"]["token"])
settings.toml
[database]
url = "postgresql://user:pass@localhost/db"
[api]
debug = true
settings.py
import tomllib
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
config_path = BASE_DIR / "settings.toml"
with open(config_path, "rb") as f:
cfg = tomllib.load(f)
DB_URL = cfg["database"]["url"]
DEBUG = cfg["api"]["debug"]
# utils/toml.py
import tomllib
import tomli_w
from pathlib import Path
from typing import Any
def load(path: str | Path) -> dict:
path = Path(path)
with open(path, "rb") as f:
return tomllib.load(f)
def save(path: str | Path, data: dict) -> None:
path = Path(path)
with open(path, "wb") as f:
tomli_w.dump(data, f)
使用:
from utils.toml import load, save
config = load("config.toml")
save("out.toml", config)
你的项目中肯定会用到。
典型 pyproject.toml:
[project]
name = "my_app"
version = "1.0.0"
requires-python = ">=3.12"
[tool.black]
line-length = 100
[tool.ruff]
select = ["E", "F"]
ignore = ["E501"]
[tool.poetry]
packages = [{ include = "app" }]
| 特性 | TOML | JSON |
|---|---|---|
| 注释支持 | ✅ | ❌ |
| 更适合人读写 | ✅ | ❌ |
| 配置分节结构 | ✅ | ❌ |
| 适合日志/配置 | ✅ | 一般 |
| 更严格(少 bug) | ✅ | ❌ |
| 支持多行字符串 | ✅ | 一般 |
所以:
- 配置文件(settings、工具配置) -> 用 TOML
- 数据传输(API) -> 用 JSON / orjson
📌 九、总结(你只需要记住这些)
- Python 3.11 内置 tomllib -> 只能读
- 写入用:tomli_w
- TOML 的结构就是:
[table][[array of table]]
- Python 读取后就是普通 dict
- 最适合作为项目配置文件