Python 3.11 你应该试试的超酷特性
Python 3.11在10月24日发布。它是Python最新版本,运行速度更快且更佳友好。在经过17个月的研发,终于到了可以使用的黄金时期。
和每个发布版本一样,Python 3.11做了大量的变更及提高。你可以通过查看文档来了解大部分内容。这里,我们会阐述最酷且最有影响力的新特性。
教程里将涵盖如下内容:
- 更好的错误信息来帮助代码追踪
- Faster CPython项目加速代码执行
- 在异步代码中使用Task和exception groups
- Python静态类型新增的几个类型特性
- 原生支持TOML格式配置文件
如果你想运行本教程所提供的示例文件,你需要先安装Python 3.11.
对TOML格式配置文件的支持
TOML是Tom's Obvious Minimal Language的缩写。是一个最近非常流行的配置文件格式。Python社区已经加TOML作为包或者项目定义metadata的可选格式。
TOML旨在设计为人类更易读,计算机更容易解析。
TOML格式已经在很多工具里用了好多年了。Python内建没有对TOML支持。Python 3.11将tomllib作为标准库。该库构建与tomli第三方库之上。
我们看看TOML格式文件示例:
# units.toml
[second]
label = { singular = "second", plural = "seconds" }
aliases = ["s", "sec", "seconds"]
[minute]
label = { singular = "minute", plural = "minutes" }
aliases = ["min", "minutes"]
multiplier = 60
to_unit = "second"
[hour]
label = { singular = "hour", plural = "hours" }
aliases = ["h", "hr", "hours"]
multiplier = 60
to_unit = "minute"
[day]
label = { singular = "day", plural = "days" }
aliases = ["d", "days"]
multiplier = 24
to_unit = "hour"
[year]
label = { singular = "year", plural = "years" }
aliases = ["y", "yr", "years", "julian_year", "julian years"]
multiplier = 365.25
to_unit = "day"
文件包含了几个区域,每个区域使用方括号命名headline。每个区域是一个table,包含了键值对。
值可以是各种类型,例子中包含:
- label是一个嵌套table,类似Python字典
- aliases是个数组,类似list
- multiplier是一个数值,可以是整型或者浮点型
- to_unit是个字符创
TOML还支持更多类型,包括布尔类型和日期类型。
我们可以使用tomllib来读取TOML文件:
>>> import tomllib
>>> with open("units.toml", mode="rb") as handle:
... units = tomllib.load(handle)
...
>>> units
{'second': {'label': {'singular': 'second', 'plural': 'seconds'}, 'aliases': ['s', 'sec', 'seconds']}, 'minute': {'label': {'singular': 'minute', 'plural': 'minutes'}, 'aliases': ['min', 'minutes'], 'multiplier': 60, 'to_unit': 'second'}, 'hour': {'label': {'singular': 'hour', 'plural': 'hours'}, 'aliases': ['h', 'hr', 'hours'], 'multiplier': 60, 'to_unit': 'minute'}, 'day': {'label': {'singular': 'day', 'plural': 'days'}, 'aliases': ['d', 'days'], 'multiplier': 24, 'to_unit': 'hour'}, 'year': {'label': {'singular': 'year', 'plural': 'years'}, 'aliases': ['y', 'yr', 'years', 'julian_year', 'julian years'], 'multiplier': 365.25, 'to_unit': 'day'}}
>>>
使用二进制模式mode="rb"获得一个文件对象,并传递给tomllib.load()。同样也可以使用字符串解析模式:
>>> import tomllib
>>> import pathlib
>>> units = tomllib.loads(
... pathlib.Path("units.toml").read_text(encoding="utf-8")
... )
>>> units
{'second': {'label': {'singular': 'second', 'plural': 'seconds'}, ... }}
这里,我们使用pathlib读取units.toml内容存储为字符串,然后传递给loads()进行解析。TOML应该使用UTF-8编码。所以这里我们指明编码格式以便再不同平台兼容。