Python 3.5 新特性全面总结
发布时间:2015 年 9 月 13 日
一、重磅新语法
1. async/await 原生协程(PEP 492)
Python 3.5 引入完整的原生协程支持,告别 @asyncio.coroutine + yield from:
python
import asyncio
# 协程函数
async def http_get(domain):
reader, writer = await asyncio.open_connection(domain, 80)
writer.write(b'GET / HTTP/1.1\r\nHost: %b\r\n\r\n' % domain.encode())
async for line in reader:
print('>>>', line)
writer.close()
# 异步上下文管理器
async def coro(name, lock):
async with lock:
print(f'coro {name} holding the lock')
await asyncio.sleep(1)
# 异步迭代
async def ticker(delay, to):
for i in range(to):
yield i
await asyncio.sleep(delay)
核心概念:
async def声明协程函数await挂起协程直到结果可用(任何实现了__await__的对象)async for遍历异步可迭代对象async with进入异步上下文管理器
2. 矩阵乘法运算符 @(PEP 465)
为 NumPy 等科学计算库提供原生矩阵乘法运算符:
python
import numpy as np
x = np.ones(3)
m = np.eye(3)
x @ m # array([ 1., 1., 1.])
# 自定义实现
class Matrix:
def __matmul__(self, other): ...
def __rmatmul__(self, other): ...
def __imatmul__(self, other): ...
3. 解包泛化(PEP 448)
* 和 ** 解包可用于更多场景:
python
# 函数调用中多次解包
print(*[1], *[2], 3, *[4, 5]) # 1 2 3 4 5
fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
# 解包用于构造
*range(4), 4 # (0, 1, 2, 3, 4)
[*range(4), 4] # [0, 1, 2, 3, 4]
{*range(4), 4, *(5, 6, 7)} # {0, 1, 2, 3, 4, 5, 6, 7}
{'x': 1, **{'y': 2}} # {'x': 1, 'y': 2}
4. bytes/bytearray 的 % 格式化(PEP 461)
python
b'Hello %b!' % b'World' # b'Hello World!'
b'x=%i y=%f' % (1, 2.5) # b'x=1 y=2.500000'
# %a: ASCII 表示(repr 风格)
b"price: %a" % '10€' # b"price: '10\\u20ac'"
5. StopIteration 处理变更(PEP 479)
生成器内部 StopIteration 现在转换为 RuntimeError:
python
from __future__ import generator_stop # 启用新行为
def gen():
next(iter([])) # StopIteration 在生成器内
yield
next(gen())
# RuntimeError: generator raised StopIteration
二、标准库新增模块
typing --- 类型提示(PEP 484)
python
def greeting(name: str) -> str:
return 'Hello ' + name
# 核心类型
from typing import List, Dict, Set, Tuple, Optional, Union, Any
def process(items: List[int]) -> Dict[str, int]:
...
# Optional[X] 相当于 Union[X, None]
# Any:与所有类型兼容
类型提示不影响运行时,供静态分析工具(mypy、pyright)使用。
zipapp --- 可执行 ZIP 应用(PEP 441)
bash
# 打包 Python 应用为单个 .pyz 文件
python -m zipapp myapp
python myapp.pyz
三、标准库重要改进
1. os.scandir() --- 更快目录遍历(PEP 471)
比 os.listdir() 更高效的目录遍历,避免重复 stat() 调用:
python
# 比 os.listdir 快 3-20 倍(Windows 提升更大)
for entry in os.scandir(path):
if entry.is_file():
print(entry.name)
# entry.inode() 无需额外 stat 调用
2. subprocess.run() --- 简化的子进程运行
新增更简洁的 subprocess.run(),替代 call()/check_call()/check_output():
python
# 3.5 新增,一行调用
result = subprocess.run(['ls', '-la'], capture_output=True, text=True)
# 等价于 3.4 的繁琐写法
try:
proc = subprocess.Popen(['ls', '-la'], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
finally:
proc.wait()
3. OrderedDict C 实现 --- 提速 4-100 倍
python
from collections import OrderedDict
# 内部实现从 Python 切换为 C,性能大幅提升
4. functools.lru_cache C 实现
python
import functools
@functools.lru_cache(maxsize=128)
def heavy_computation(x):
...
# 大部分逻辑改为 C 实现,速度显著提升
5. math.isclose() --- 近似相等判断(PEP 485)
python
import math
math.isclose(5.0, 4.99998, rel_tol=1e-5) # True(相对误差)
math.isclose(5.0, 4.99998, abs_tol=0.00003) # True(绝对误差)
6. bytes.hex() / bytearray.hex()
python
b'hello'.hex() # '68656c6c6f'
bytearray(b'hello').hex() # '68656c6c6f'
# 解码
bytes.fromhex('68656c6c6f') # b'hello'
7. RecursionError 新异常
python
# 递归深度超限时明确抛出 RecursionError
def f(): f()
f()
# RecursionError: maximum recursion depth exceeded
8. 生成器新属性 gi_yieldfrom
python
def gen():
yield from range(3)
g = gen()
g.gi_yieldfrom # range(3) 对象
9. 系统调用 EINTR 自动重试(PEP 475)
以下函数遇到信号中断自动重试,无需手动处理 InterruptedError:
python
open(), read(), write(), select(), socket.accept/connect/recv/send,
time.sleep() 等
10. 其他改进
python
# heapq.merge 支持 key 和 reverse
list(heapq.merge(a, b, key=len, reverse=True))
# glob 递归搜索
list(glob.glob('**/*.py', recursive=True))
# compileall 并行编译
python -m compileall -j 4 mydir/
# contextlib.redirect_stderr
with redirect_stderr(f):
logging.warning('warning')
# http.HTTPStatus 枚举
from http import HTTPStatus
HTTPStatus.OK # 200
# enum.Enum 支持 start 参数
Animal = Enum('Animal', 'cat dog', start=10)
# imaplib 支持上下文管理器
with imaplib.IMAP4_SSL(server) as mail:
...
# configparser 自定义转换器
cfg.getlist('s', 'list') # 自定义 list 转换
四、安全改进
- SSLv3 全面禁用(可手动启用)
- HTTP Cookie 解析更严格(防止注入攻击)
- 生成器异常处理改进(避免静默 bug)
五、Windows 改进
- 虚拟环境感知 (PEP 486):
VIRTUAL_ENV环境变量被 py.exe 识别 - 新安装程序替代旧 MSI
- 使用 Visual C++ 14.0 构建
六、导入系统改进
- PYO 文件废除 (PEP 488):优化字节码用
__pycache__/*.opt-*.pyc区分 - 多阶段扩展模块初始化(PEP 489):导入语义与 Python 模块统一,支持任意 Unicode 模块名
总结
Python 3.5 的核心亮点:
- async/await 原生协程 --- 革命性的异步编程语法
- 矩阵乘法
@运算符 --- NumPy 集成的基础 - 解包泛化
*--- 函数调用和构造中的多重解包 - typing 模块 --- 类型提示标准化的起点
os.scandir()--- 目录遍历快 3-20 倍subprocess.run()--- 子进程运行简化OrderedDict/lru_cacheC 实现 --- 标准库性能大幅提升math.isclose()--- 浮点数近似比较- EINTR 自动重试 --- 系统调用更健壮
RecursionError异常 --- 递归深度错误明确化
Python 3.5 是一个异步编程元年的版本。async/await 语法的引入彻底改变了 Python 异步编程的生态,让协程从第三方库(gevent/tornado)一跃成为语言内置的一等公民。而 typing 模块的引入也为后续版本的类型系统演进奠定了基础。
参考:Python 3.5 官方文档 - What's New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。