Python 3.5 新特性全面总结

Python 3.5 新特性全面总结

发布时间:2015 年 9 月 13 日

官方文档:https://docs.python.org/zh-cn/3.5/whatsnew/3.5.html


一、重磅新语法

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 的核心亮点:

  1. async/await 原生协程 --- 革命性的异步编程语法
  2. 矩阵乘法 @ 运算符 --- NumPy 集成的基础
  3. 解包泛化 * --- 函数调用和构造中的多重解包
  4. typing 模块 --- 类型提示标准化的起点
  5. os.scandir() --- 目录遍历快 3-20 倍
  6. subprocess.run() --- 子进程运行简化
  7. OrderedDict / lru_cache C 实现 --- 标准库性能大幅提升
  8. math.isclose() --- 浮点数近似比较
  9. EINTR 自动重试 --- 系统调用更健壮
  10. RecursionError 异常 --- 递归深度错误明确化

Python 3.5 是一个异步编程元年的版本。async/await 语法的引入彻底改变了 Python 异步编程的生态,让协程从第三方库(gevent/tornado)一跃成为语言内置的一等公民。而 typing 模块的引入也为后续版本的类型系统演进奠定了基础。


参考:Python 3.5 官方文档 - What's New

内容由 AI 整理生成,内容仅供参考,请仔细甄别。

相关推荐
野生的小狗熊1 小时前
【自学Agent开发之路】第二篇—从.NET到Python:Agent开发的本质就是投喂上下文
python
牵牛花主人1 小时前
【无标题】
python·pandas
abcy0712131 小时前
sqlalchemy 原生sql判断条件是否为空,为空则跳过
开发语言·python
知识分享小能手1 小时前
数据预处理入门学习教程,从入门到精通, 实战演练——数据分析师岗位分析知识点详解(8)
python·学习·信息可视化
Wonderful U1 小时前
Python+Django实战:打造智能生鲜果蔬进销存管理系统(采购入库、库存预警、销售开单、毛利统计)
数据库·python·django
yuhuofei20211 小时前
【Python入门】Python中的集合set
python
大雨淅淅2 小时前
【机器人】ROS2 机械臂控制(MoveIt2)从入门到实战
人工智能·python·神经网络·学习·算法·机器学习·机器人
张哈大2 小时前
MCP:重塑AI工具调用的统一标准,告别重复造轮子的时代
人工智能·python·ai·prompt
极光代码工作室2 小时前
基于深度学习的智能图像识别平台
python·深度学习·机器学习·ai·系统设计