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 和内存资源。 建议对要解析的数据大小进行限制。

参见

Tomli-W 包 是一个 TOML 写入器,它可以与此模块一起使用,提供了与标准库用户熟悉的 marshalpickle 模块类似的写入 API。

参见

TOML Kit 包 是一个兼具读取和写入功能的保留样式的 TOML 库。 它是用于编辑现有 TOML 文件的本模块的推荐替代品。

这个模块定义了以下函数:

tomllib.load(fp, /, *, parse_float=float)

读取一个 TOML 文件。第一个参数应该是一个可读的二进制文件对象。返回 dict。使用 转换表 将 TOML 类型转换为 Python。

对每个要解析的 TOML 浮点数字符串调用 parse_float。 默认情况下,这相当于 float(num_str)。这可以用于为 TOML 浮点数使用另一种数据类型或解析器 (例如 decimal.Decimal)。 可调用对象不能返回 dictlist,否则将引发 ValueError

对无效的 TOML 文档将引发 TOMLDecodeError

tomllib.loads(s, /, *, parse_float=float)

str 对象中加载 TOML。返回 dict。使用 转换表 将 TOML 类型转换为 Python类型。参数 parse_floatload() 中的意义相同。

对无效的 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 版本发生变更: 增加了 msg, docpos 形参。 增加了 msg, doc, pos, linenocolno 属性。

自 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 (tzinfo 属性设置为 datetime.timezone 的实例)

local date-time

datetime.datetime (tzinfo 属性设置为 None)

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 实现细节: tomllib loads dictionary entries in the order they appear in the source.

整数

TOML recommends supporting integers in range(−2**63, 2**63).

CPython 实现细节: tomllib uses 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 实现细节: tomllib uses Python float by default; on many common platforms this is the recommended binary64. See sys.float_info for 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's recursion limit. Note that code that calls tomllib may contribute to the limit.