python 新特性
📅 版本概览
- Python 3.7 (2018.6) - 异步增强
- Python 3.8 (2019.10) - 海象运算符
- Python 3.9 (2020.10) - 字典合并
- Python 3.10 (2021.10) - 模式匹配
- Python 3.11 (2022.10) - 性能革命
- Python 3.12 (2023.10) - 类型增强
# 查看当前 Python 版本的新特性 python -m whatsnew # 查看特定版本的新特性 python -m whatsnew 3.11 #或者 import sys from importlib.metadata import version print(f"Python {sys.version}") print(f"完整版本: {sys.version_info}") print(f"新特性文档: https://docs.python.org/{sys.version_info.major}.{sys.version_info.minor}/whatsnew/")
🚀 Python 3.7 新特性
-
1. 数据类(Data Classes)
from dataclasses import dataclass, field from typing import List @dataclass class User: name: str age: int email: str = "未设置" friends: List[str] = field(default_factory=list) def greet(self): return f"你好,我是{self.name},{self.age}岁" # 自动生成 __init__, __repr__, __eq__ 等方法 user = User("张三", 25, "zhang@example.com") print(user) # User(name='张三', age=25, email='zhang@example.com', friends=[]) print(user.greet()) # 你好,我是张三,25岁
2. 异步生成器(Async Generators)
import asyncio async def async_counter(max: int): for i in range(max): await asyncio.sleep(0.1) # 模拟IO操作 yield i async def main(): # 异步迭代 async for num in async_counter(5): print(f"计数: {num}") # 异步推导式 result = [i async for i in async_counter(3)] print(f"结果: {result}") # [0, 1, 2] # asyncio.run(main())
🎯 Python 3.8 新特性
1. 海象运算符(Walrus Operator :=)
# 传统写法 while True: line = input("请输入: ") if not line: break print(f"你输入了: {line}") # 海象运算符 while (line := input("请输入: ")) : print(f"你输入了: {line}") # 列表推导式中使用 data = [1, 2, 3, 4, 5] results = [(x, y) for x in data if (y := x * 2) > 6] print(results) # [(4, 8), (5, 10)] # 正则匹配 import re text = "价格: 100元, 折扣: 20%" if match := re.search(r'价格: (\d+)元', text): price = int(match.group(1)) print(f"价格: {price}") # 价格: 100
Python 3.9 新特性
1. 字典合并与更新运算符
# 字典合并 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} # 字典推导式 data = {"user1": 100, "user2": 200} inverted = {v: k for k, v in data.items()} print(inverted) # {100: 'user1', 200: 'user2'}
2. 字符串方法
# 移除前缀/后缀 text = "test_string.txt" print(text.removesuffix(".txt")) # test_string print(text.removeprefix("test_")) # string.txt # 分割行保持换行符 text = "line1\nline2\nline3" lines = text.splitlines(keepends=True) print(lines) # ['line1\n', 'line2\n', 'line3']
Python 3.10 新特性
1. 结构模式匹配(Match-Case)
def handle_command(command): match command.split(): case ["quit"]: return "退出程序" case ["load", filename]: return f"加载文件: {filename}" case ["save", filename]: return f"保存到: {filename}" case ["delete", *filenames] if len(filenames) > 0: return f"删除文件: {', '.join(filenames)}" case ["search", query, "in", *locations]: return f"在 {', '.join(locations)} 搜索: {query}" case _: return f"未知命令: {command}" # 测试 print(handle_command("load data.txt")) # 加载文件: data.txt print(handle_command("delete file1.txt file2.txt")) # 删除文件: file1.txt, file2.txt
2. 类型联合运算符
# 旧写法 from typing import Union def process(value: Union[int, str, None]) -> Union[int, str]: pass # 新写法 def process(value: int | str | None) -> int | str: pass # 在 isinstance 中使用 value = 100 if isinstance(value, int | float): print(f"{value} 是数字") # 在类型别名中使用 Number = int | float def add(a: Number, b: Number) -> Number: return a + b
3. 带括号的上下文管理器
# 多个上下文管理器 with ( open("input.txt") as f1, open("output.txt", "w") as f2, open("log.txt", "a") as f3 ): data = f1.read() f2.write(data.upper()) f3.write("处理完成\n") # 长表达式 with (open("data.txt") as file, suppress(FileNotFoundError)): process(file.read())
⚡ Python 3.11 新特性
1. 异常组和 except*
def task1(): raise ValueError("任务1错误") def task2(): raise TypeError("任务2错误") def task3(): return "任务3成功" try: # 同时执行多个任务 import asyncio from asyncio import TaskGroup async def main(): async with TaskGroup() as tg: tg.create_task(task1()) tg.create_task(task2()) tg.create_task(task3()) asyncio.run(main()) except* ValueError as eg: print(f"ValueError: {eg.exceptions}") except* TypeError as eg: print(f"TypeError: {eg.exceptions}")
2.Self 类型
from typing import Self class Database: def __init__(self, url: str): self.url = url @classmethod def from_config(cls, config: dict) -> Self: """返回当前类的实例""" return cls(config["url"]) def with_timeout(self, timeout: int) -> Self: """返回修改后的自身实例""" self.timeout = timeout return self class MySQLDatabase(Database): def ping(self) -> bool: return True # 类型检查能正确推断 db = MySQLDatabase.from_config({"url": "localhost"}) result = db.with_timeout(30).ping() # ✅ 正确
3. 性能提升
# 3.11 比 3.10 快 25-60% import timeit # 简单循环 code = """ total = 0 for i in range(1000000): total += i """ time = timeit.timeit(code, number=100) print(f"执行时间: {time:.2f}秒")
🆕 Python 3.12 新特性
1. 类型参数语法(PEP 695)
# 旧写法 from typing import TypeVar, Generic T = TypeVar("T") class Container(Generic[T]): def __init__(self, value: T): self.value = value # 新写法 class Container[T]: def __init__(self, value: T): self.value = value def get_value(self) -> T: return self.value # 使用 int_container = Container[int](42) str_container = Container[str]("hello") # 函数类型参数 def first[T](items: list[T]) -> T: return items[0] print(first([1, 2, 3])) # 1 print(first(["a", "b", "c"])) # "a"
2. 缓冲协议(PEP 688)
import array def process_buffer(buff: Buffer) -> None: """处理任意缓冲区对象""" print(f"缓冲区大小: {len(buff)}") print(f"缓冲区格式: {buff.format}") # 可以直接索引访问 for i in range(min(10, len(buff))): print(f"buff[{i}] = {buff[i]}") # 可以处理多种类型 arr = array.array('i', [1, 2, 3, 4, 5]) process_buffer(arr) import numpy as np np_arr = np.array([1.0, 2.0, 3.0]) process_buffer(np_arr)
3. 子解释器 API
import _xxsubinterpreters as interpreters # 创建子解释器 interp_id = interpreters.create() # 在子解释器中运行代码 code = """ import sys print(f"子解释器: {sys.implementation.name}") """ interpreters.run_string(interp_id, code) # 清理 interpreters.destroy(interp_id)
📊 新特性快速参考表
| 版本 | 关键特性 | 使用场景 |
|---|---|---|
| 3.7 | Data Classes, async/await 增强 | API 模型、异步编程 |
| 3.8 | 海象运算符、位置参数 | 简化代码、API 设计 |
| 3.9 | 字典合并、类型提示简化 | 数据处理、类型安全 |
| 3.10 | 模式匹配、联合类型 | 条件分支、状态机 |
| 3.11 | 异常组、Self 类型、性能 | 并发错误处理、OOP |
| 3.12 | 类型参数、缓冲协议 | 泛型编程、高性能计算 |
💡 迁移建议
检查当前Python版本
import sys print(f"Python {sys.version}") print(f"版本信息: {sys.version_info}")
使用新特性的兼容性检查
当然上边例举的都是经典的,还有一些没有细分
📋 完整的新特性清单
Python 3.7 遗漏特性
- contextvars 模块:上下文变量管理
- importlib.resources:资源文件访问
- time.perf_counter_ns():纳秒级计时器
- asyncio.run():简化异步入口
Python 3.8 遗漏特性
- f-string = 调试语法:
f"{name=}" - math.prod():计算乘积
- functools.cached_property:缓存属性装饰器
- pickle 协议 5:支持内存视图
Python 3.9 遗漏特性
- zoneinfo 模块:时区处理
- graphlib.TopologicalSorter:拓扑排序
- random.Random.randbytes():生成随机字节
- unittest.IsolatedAsyncioTestCase:异步单元测试
Python 3.10 遗漏特性
- parenthesized context managers:带括号的上下文管理器
- PEP 634-636:模式匹配的完整规范
- distutils 弃用:迁移到 setuptools
- typing.Required/NotRequired:可选字典键
Python 3.11 遗漏特性
- ExceptionGroup 和 except*:异常组处理
- tomllib 模块:解析 TOML 文件
- typing.Self:返回自身类型
- typing.LiteralString:字面字符串类型
- typing.Never:永不返回的类型
Python 3.12 遗漏特性
- PEP 701:f-string 语法改进:更灵活的 f-string
- PEP 684:per-interpreter GIL:子解释器 GIL
- PEP 709:内联推导式:推导式性能优化
- typing.override 装饰器:重写方法检查
本文来自博客园,作者:南鱼羁荒渡,转载请注明原文链接:https://www.cnblogs.com/nanyu/p/19355716
浙公网安备 33010602011771号