Python 新特性
问题
Python 3.8 到 3.13 有哪些重要的新特性?
答案
Python 3.8 — 海象运算符
# 赋值表达式 :=(Walrus Operator)
# 在表达式中赋值,减少重复计算
if (n := len(data)) > 10:
print(f"数据量 {n} 超过限制")
# 列表推导中过滤 + 使用
results = [y for x in data if (y := expensive(x)) is not None]
# 仅位置参数 /
def divmod(a, b, /): # a、b 只能按位置传递
return a // b, a % b
Python 3.9 — 类型提示简化
# 内置类型直接用于类型提示(不再需要 from typing import List)
def process(items: list[int]) -> dict[str, int]:
return {str(i): i for i in items}
# 字典合并运算符
a = {"x": 1}
b = {"y": 2}
merged = a | b # {"x": 1, "y": 2}
a |= b # 原地合并
Python 3.10 — 模式匹配
# match/case(结构化模式匹配)
def handle_command(command):
match command.split():
case ["quit"]:
return "退出"
case ["go", direction]:
return f"前往 {direction}"
case ["get", item] if item != "sword":
return f"拾取 {item}"
case _:
return "未知命令"
# 更简洁的联合类型
def square(n: int | float) -> int | float: # 替代 Union[int, float]
return n ** 2
Python 3.11 — 性能提升
# 速度提升 10-60%(Faster CPython 项目)
# 异常组和 except*
async def fetch_all():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch_a())
tg.create_task(fetch_b())
except* ValueError as eg:
for e in eg.exceptions:
print(f"值错误: {e}")
except* TypeError as eg:
for e in eg.exceptions:
print(f"类型错误: {e}")
# 更精确的错误提示
# x = 1 / 0
# ~~^~~
# ZeroDivisionError
Python 3.12 — 类型参数语法
# 新泛型语法(不再需要 TypeVar)
def first[T](lst: list[T]) -> T: # 泛型函数
return lst[0]
class Stack[T]: # 泛型类
def __init__(self) -> None:
self.items: list[T] = []
def push(self, item: T) -> None:
self.items.append(item)
# f-string 嵌套
print(f"{'hello':>10}") # 现在支持更复杂的嵌套表达式
Python 3.13 — 自由线程
# 实验性:无 GIL(Free-threaded CPython)
# 编译时启用:./configure --disable-gil
# 真正的多线程并行 CPU 密集型任务
# 改进的交互式解释器(基于 PyREPL)
# 彩色输出、多行编辑、更好的自动补全
# 改进的错误消息
# 'hello' + 42
# TypeError: can only concatenate str (not "int") to str
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Did you mean to convert the int to str? Use str(42)
特性总结
| 版本 | 代表特性 | 面试价值 |
|---|---|---|
| 3.8 | := 海象运算符、/ 仅位置参数 | ⭐⭐⭐ |
| 3.9 | list[int] 类型提示、| 字典合并 | ⭐⭐⭐ |
| 3.10 | match/case、X | Y 联合类型 | ⭐⭐⭐⭐ |
| 3.11 | 性能提升、except*、TaskGroup | ⭐⭐⭐⭐ |
| 3.12 | def f[T]() 泛型语法、f-string 增强 | ⭐⭐⭐ |
| 3.13 | 无 GIL 实验、改进的 REPL | ⭐⭐⭐⭐ |