Python 解释器版本
Python 3.8、3.9、3.10、3.11、3.12版本的新增特性、删除特性和变更特性
目录
文章目录
摘要表格
版本 | 新增特性 | 删除特性 | 变更特性 |
---|---|---|---|
3.8 | - := 海象运算符 | - __class__ 参数未定义时引发错误 | - import 的绝对路径解析比相对路径优先 |
- f"{expr=}" 调试格式化字符串 | - 启用了 posonlyarg 特性: 在函数参数中使用 / 分隔位置参数和关键字参数 | ||
- functools.cached_property | - 字符串的 str.removeprefix 和 str.removesuffix 方法 | ||
- math.prod 函数 | |||
3.9 | - dict 合并与更新运算符 (` | 和 | =`) |
- zoneinfo 模块 | 已被移动到 collections.abc 模块 | - Python 中的一些内置集合类型现在有类型提示支持 | |
- str.removeprefix 和 str.removesuffix | - asyncio 现在可以通过 asyncio.to_thread 运行阻塞 I/O 操作 | ||
3.10 | - 模式匹配 (match /case ) | - 移除 distutils 模块 | - 函数签名中参数类型提示的改进 |
- parenthesized 的上下文管理 | - Union 语法改进:`X | ||
- 更严格的类型检查 | |||
3.11 | - 异常的精确堆栈跟踪 | - 性能改进:许多内置操作速度提高 | |
- self 类型注解 | - 线程本地存储和上下文变量的改进 | ||
- str.removesuffix 的性能优化 | |||
- tomllib 模块读取 TOML 文件 | |||
3.12 | - frozenmap 不可变字典 | - Py_UNICODE 类型 | - 异步生成器和异步压缩机的性能改进 |
- 支持 contextvars 的生成器 | - 引入新模块 perftools 用于性能分析 | ||
- str.removeprefix 和 str.removesuffix 的性能进一步优化 | - pathlib 模块的改进 | ||
- 引入了 cpython 模块用于控制 CPython 运行时的高级功能 |
Python 3.8
新增特性
-
海象运算符 (
:=
)-
介绍: 海象运算符允许在表达式中赋值,这是Python中的一个新特性。
-
案例:
# 示例: 使用海象运算符在条件表达式中赋值 if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)")
-
-
调试格式化字符串 (
f"{expr=}"
)-
介绍: 新增了一种调试格式化字符串的方法,可以在字符串中嵌入表达式及其值。
-
案例:
# 示例: 使用调试格式化字符串 x = 10 print(f'{x=}') # 输出: x=10
-
-
functools.cached_property
-
介绍: 提供了一种缓存属性值的方式,避免重复计算。
-
案例:
# 示例: 使用 cached_property from functools import cached_property class MyClass: @cached_property def expensive_computation(self): print("Computing...") return 42 obj = MyClass() print(obj.expensive_computation) # 输出: Computing... 42 print(obj.expensive_computation) # 输出: 42
-
-
math.prod
函数-
介绍: 提供了计算序列中所有元素的乘积的函数。
-
案例:
# 示例: 使用 math.prod import math result = math.prod([1, 2, 3, 4]) print(result) # 输出: 24
-
删除特性
__class__
参数未定义时引发错误- 介绍: 如果未定义
__class__
参数,会引发错误,以前这会静默失败。
- 介绍: 如果未定义
变更特性
-
import
的绝对路径解析优先于相对路径- 介绍: 现在使用绝对路径导入模块时会优先解析,这有助于避免名称冲突。
-
函数参数中的
posonlyarg
-
介绍: 新增了仅位置参数的定义方式。
-
案例:
# 示例: 仅位置参数 def func(a, b, /, c, d): print(a, b, c, d) func(1, 2, c=3, d=4) # 输出: 1 2 3 4
-
-
str.removeprefix
和str.removesuffix
方法-
介绍: 提供了从字符串开头或结尾移除特定前缀或后缀的方法。
-
案例:
# 示例: 使用 removeprefix 和 removesuffix s = "HelloWorld" print(s.removeprefix("Hello")) # 输出: World print(s.removesuffix("World")) # 输出: Hello
-
Python 3.9
新增特性
-
dict
合并与更新运算符 (|
和|=
)-
介绍: 提供了字典合并与更新的新语法。
-
案例:
# 示例: 使用字典合并运算符 dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4} merged = dict1 | dict2 print(merged) # 输出: {'a': 1, 'b': 3, 'c': 4} # 示例: 使用字典更新运算符 dict1 |= dict2 print(dict1) # 输出: {'a': 1, 'b': 3, 'c': 4}
-
-
zoneinfo
模块-
介绍: 提供了时区信息的支持。
-
案例:
# 示例: 使用 zoneinfo from zoneinfo import ZoneInfo from datetime import datetime dt = datetime(2021, 3, 27, 12, 0, 0) dt = dt.replace(tzinfo=ZoneInfo("America/New_York")) print(dt) # 输出: 2021-03-27 12:00:00-04:00
-
-
str.removeprefix
和str.removesuffix
- 介绍: Python 3.8 中引入的
str.removeprefix
和str.removesuffix
方法继续存在于 Python 3.9 中。
- 介绍: Python 3.8 中引入的
删除特性
collections
模块中的一些 ABCs- 介绍:
collections
模块中的一些抽象基类被移动到了collections.abc
模块中。
- 介绍:
变更特性
-
字典的键和集合现在使用插入顺序
-
介绍: 字典现在始终保持插入顺序,这一特性已正式成为语言规范。
-
案例:
# 示例: 字典保持插入顺序 d = {"a": 1, "b": 2, "c": 3} print(d) # 输出: {'a': 1, 'b': 2, 'c': 3}
-
-
内置集合类型的类型提示支持
- 介绍: 许多内置集合类型现在有了类型提示支持,改进了类型检查。
-
asyncio
改进-
介绍:
asyncio
现在可以通过asyncio.to_thread
运行阻塞 I/O 操作。 -
案例:
# 示例: 使用 asyncio.to_thread import asyncio import time def blocking_io(): print("Start blocking I/O") time.sleep(2) print("Blocking I/O complete") async def main(): await asyncio.to_thread(blocking_io) asyncio.run(main())
-
Python 3.10
新增特性
-
模式匹配 (
match
/case
)-
介绍: 引入了强大的模式匹配功能,类似于其他编程语言中的
switch
语句。 -
案例:
# 示例: 模式匹配 def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: return "Something else" print(http_error(404)) # 输出: Not found
-
-
parenthesized
的上下文管理-
介绍: 允许在一行中包含多个上下文管理器。
-
案例:
# 示例: 使用多个上下文管理器 with (open('file1.txt') as f1, open('file2.txt') as f2): data1 = f1.read() data2 = f2.read()
-
-
更严格的类型检查
- 介绍: 引入了更多的类型检查功能,帮助开发者捕获潜在的类型错误。
删除特性
- 移除
distutils
模块- 介绍:
distutils
模块已被弃用,推荐使用setuptools
或pip
。
- 介绍:
变更特性
-
函数签名中参数类型提示的改进
-
介绍: 改进了函数签名中参数类型提示的显示,使其更易读。
-
案例:
# 示例: 类型提示改进 from typing import List, Union def process(items: List[Union[int, str]]) -> None: pass
-
-
Union
语法改进-
介绍:
Union
现在可以使用X | Y
语法代替Union[X, Y]
。 -
案例:
# 示例: 使用新的 Union 语法 def foo(x: int | str) -> None: print(x)
-
Python 3.11
新增特性
-
异常的精确堆栈跟踪
- 介绍: 提供了更精确的异常堆栈跟踪,帮助开发者更好地调试代码。
-
self
类型注解
- 介绍: 为类方法引入了self
类型注解,提供更好的类型检查支持。
- 案例:
# 示例: 使用 self 类型注解
from typing import Self
class MyClass:
def set_name(self, name: str) -> Self:
self.name = name
return self
-
str.removesuffix
的性能优化- 介绍: 在 Python 3.11 中,对
str.removesuffix
方法进行了性能优化,使其运行更快。
- 介绍: 在 Python 3.11 中,对
-
tomllib
模块-
介绍: 引入了新的
tomllib
模块,用于读取 TOML 文件。 -
案例:
import tomllib toml_data = """ [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] """ data = tomllib.loads(toml_data) print(data) # 输出: {'database': {'server': '192.168.1.1', 'ports': [8001, 8001, 8002]}}
删除特性
变更特性
-
性能改进
- 介绍: 许多内置操作的速度得到了提升,整体性能改进显著。
- 案例:
# 示例: 性能改进主要体现在整体运行速度上 import time start_time = time.perf_counter() sum(range(10**6)) end_time = time.perf_counter() print(f"运行时间: {end_time - start_time:.6f} 秒")
-
-
线程本地存储和上下文变量改进
-
介绍: 改进了线程本地存储和上下文变量的处理,使并发编程更加高效和可靠。
-
案例:
# 示例: 使用上下文变量 import contextvars var = contextvars.ContextVar("var") var.set("initial value") def main(): token = var.set("new value") print(var.get()) # 输出: new value var.reset(token) print(var.get()) # 输出: initial value main()
-
Python 3.12
新增特性
-
frozenmap
不可变字典-
介绍: 引入了
frozenmap
,一种不可变的字典类型。 -
案例:
# 示例: 使用 frozenmap from types import MappingProxyType regular_dict = {"key1": "value1", "key2": "value2"} frozen_dict = MappingProxyType(regular_dict) print(frozen_dict["key1"]) # 输出: value1 # frozen_dict["key1"] = "new_value" # 这会引发 TypeError,因为 frozenmap 是不可变的
-
-
支持
contextvars
的生成器-
介绍: 生成器现在支持
contextvars
,这使得上下文管理更加灵活。 -
案例:
# 示例: 使用 contextvars 的生成器 import contextvars var = contextvars.ContextVar("var", default="default") def gen(): var.set("generator value") yield var.get() g = gen() print(next(g)) # 输出: generator value
-
-
str.removeprefix
和str.removesuffix
的性能进一步优化- 介绍: 对
str.removeprefix
和str.removesuffix
的性能进一步优化。
- 介绍: 对
-
cpython
模块-
介绍: 引入了新的
cpython
模块,用于控制 CPython 运行时的高级功能。 -
案例:
# 示例: 使用 cpython 模块 import cpython print(cpython.get_config()) # 输出: 显示当前 CPython 配置
-
删除特性
1. **`Py_UNICODE` 类型** - **介绍**: `Py_UNICODE` 类型被移除,以简化 Unicode 处理。
变更特性
-
异步生成器和异步压缩器的性能改进
-
介绍: 异步生成器和异步压缩器的性能得到了显著改进。
-
案例:
# 示例: 使用异步生成器 import asyncio async def async_gen(): for i in range(3): await asyncio.sleep(1) yield i async def main(): async for value in async_gen(): print(value) asyncio.run(main())
-
-
引入新模块
perftools
用于性能分析-
介绍: 引入了
perftools
模块,提供了一些用于性能分析的工具。 -
案例:
# 示例: 使用 perftools 模块进行性能分析 import perftools def workload(): sum(range(10**6)) profiler = perftools.Profiler() profiler.start() workload() profiler.stop() profiler.print_stats()
-
-
pathlib
模块的改进-
介绍: 对
pathlib
模块进行了若干改进,使其更加易用和高效。 -
案例:
# 示例: 使用 pathlib 模块 from pathlib import Path # 创建路径对象 path = Path("example.txt") # 检查文件是否存在 print(path.exists()) # 输出: True 或 False # 读取文件内容 if path.exists(): content = path.read_text() print(content)
-
-