tomllib --- 解析 TOML 文件¶
源代码: Lib/tomllib
此模块提供了一个用于解析 TOML 1.1.0 (Tom's Obvious Minimal Language, https://toml.io) 的接口。 此模块不支持写入 TOML。
Added in version 3.11: 此模块增加了对 TOML 1.0.0 的支持。
在 3.15 版本发生变更: 增加 TOML 1.1.0 支持。 详情参见 有什么新变化。
警告
在解析不受信任来源的数据时要小心谨慎。 恶意的 TOML 字符串可能导致解码器消耗大量 CPU 和内存资源。 建议对要解析的数据大小进行限制。
参见
TOML Kit 包 是一个兼具读取和写入功能的保留样式的 TOML 库。 它是用于编辑现有 TOML 文件的本模块的推荐替代品。
这个模块定义了以下函数:
- tomllib.load(fp, /, *, parse_float=float)¶
读取一个 TOML 文件。第一个参数应该是一个可读的二进制文件对象。返回
dict。使用 转换表 将 TOML 类型转换为 Python。对每个要解析的 TOML 浮点数字符串调用 parse_float。 默认情况下,这相当于
float(num_str)。这可以用于为 TOML 浮点数使用另一种数据类型或解析器 (例如decimal.Decimal)。 可调用对象不能返回dict或list,否则将引发ValueError。对无效的 TOML 文档将引发
TOMLDecodeError。
- tomllib.loads(s, /, *, parse_float=float)¶
从
str对象中加载 TOML。返回dict。使用 转换表 将 TOML 类型转换为 Python类型。参数 parse_float 与load()中的意义相同。对无效的 TOML 文档将引发
TOMLDecodeError。
有以下几种异常:
- exception tomllib.TOMLDecodeError(msg, doc, pos)¶
拥有以下附加属性的
ValueError的子类:- msg¶
未格式化的错误消息。
- doc¶
正在解析的 TOML 文档。
- pos¶
doc 解析失败的索引位置。
- lineno¶
The line corresponding to pos.
- colno¶
The column corresponding to pos.
自 3.14 版本弃用: 传入自由形式的位置形参的做法已被弃用。
例子¶
解析 TOML 文件:
import tomllib
with open("pyproject.toml", "rb") as f:
data = tomllib.load(f)
解析 TOML 字符串:
import tomllib
toml_str = """
python-version = "3.11.0"
python-implementation = "CPython"
"""
data = tomllib.loads(toml_str)
转换表¶
TOML |
Python |
|---|---|
TOML 文档 |
dict |
string |
str |
integer |
int |
float |
float(可用 parse_float 配置) |
boolean |
bool |
offset date-time |
datetime.datetime ( |
local date-time |
datetime.datetime ( |
local date |
datetime.date |
local time |
datetime.time |
array |
list |
table |
dict |
内联表 |
dict |
表数组 |
字典列表 |
限制及互操作性的考量¶
tomllib 对其可处理的文档设定了一些限制,并保留了其他 TOML 解析器允许忽略的细节。 在编写可移植的 TOML 文件时,请仅使用标准中保证或推荐的特性。
在此列出的实现细节可能在未来的 Python 版本中发生变化。
- 表/字典
The TOML spec does not guarantee key/value pairs in TOML documents and tables to be in any specific order.
CPython 实现细节:
tomllibloads dictionary entries in the order they appear in the source.- 整数
TOML recommends supporting integers in
range(−2**63, 2**63).CPython 实现细节:
tomllibuses Python's limit on integer string conversion (4300 digits by default).- Floats
TOML recommends supporting at least IEEE 754 binary64 values, which means that numbers with more than 15 significant decimal digits are likely to be rounded.
CPython 实现细节:
tomllibuses Pythonfloatby default; on many common platforms this is the recommended binary64. Seesys.float_infofor details.- Nesting limit
TOML 1.1.0 does not recommend a limit on how deeply arrays and tables may be nested inside one another. (A limit of 100 has been proposed for a future version of TOML.)
CPython 实现细节: In
tomllib, the nesting level is mainly limited by Python'srecursion limit. Note that code that callstomllibmay contribute to the limit.