Python 3.4 新特性全面总结

Python 3.4 新特性全面总结

发布时间:2014 年 3 月 16 日

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


一、标准库新增模块

1. asyncio --- 异步 IO 框架(PEP 3156)

Python 3.4 引入 asyncio(临时 API,后续版本逐步稳定):

python 复制代码
import asyncio

@asyncio.coroutine
def http_get(url):
    reader, writer = yield from asyncio.open_connection(url, 80)
    writer.write(b'GET / HTTP/1.1\r\n\r\n')
    data = yield from reader.read()
    writer.close()
    return data

loop = asyncio.get_event_loop()
result = loop.run_until_complete(http_get('example.com'))

2. enum --- 枚举类型(PEP 435)

python 复制代码
from enum import Enum, auto

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)        # Color.RED
print(Color.RED.value)  # 1
print(Color.RED.name)   # 'RED'

3. pathlib --- 面向对象文件系统路径(PEP 428)

python 复制代码
from pathlib import Path

p = Path('/home/user/file.txt')
p.exists()           # True
p.parent / 'other'   # Path('/home/user/other')
p.write_text('data')  # 写入文件

# 遍历
for f in Path('.').glob('**/*.py'):
    print(f)

4. statistics --- 基础统计模块(PEP 450)

python 复制代码
import statistics

data = [2, 4, 4, 4, 5, 5, 7, 9]
statistics.mean(data)     # 平均值
statistics.median(data)  # 中位数
statistics.mode(data)    # 众数
statistics.variance(data)   # 方差
statistics.stdev(data)      # 标准差

5. tracemalloc --- 内存分配追踪(PEP 454)

用于追踪 Python 内存分配,帮助定位内存泄漏:

python 复制代码
import tracemalloc

tracemalloc.start()

# ... 你的代码 ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

for stat in top_stats[:5]:
    print(stat)

# 检测内存泄漏
tracemalloc.clear_traces()

6. selectors --- 高效 IO 多路复用

高层封装 select/epoll/kqueue,跨平台 I/O 多路复用。

python 复制代码
import selectors

selector = selectors.DefaultSelector()
selector.register(file_obj, selectors.EVENT_READ, data=data)

7. ensurepip --- pip 引导(PEP 453)

python 复制代码
import ensurepip
ensurepip.upgrade()  # 升级 pip

二、标准库重要改进

1. functools.singledispatch --- 单分派泛型函数(PEP 443)

根据第一个参数类型调用不同实现:

python 复制代码
from functools import singledispatch

@singledispatch
def process(x):
    """默认实现"""
    return str(x)

@process.register(int)
def _(x):
    return f"整数: {x}"

@process.register(str)
def _(x):
    return f"字符串: {x.upper()}"

process(10)       # '整数: 10'
process("hello")  # '字符串: HELLO'

2. functools.partialmethod --- 偏方法

python 复制代码
from functools import partialmethod

class Cell:
    def __init__(self):
        self._alive = False

    def set_alive(self):
        self._alive = True

    def set_dead(self):
        self._alive = False

    # 绑定第一个参数 self
    set_living = partialmethod(set_alive)
    set_deceased = partialmethod(set_dead)

3. contextlib 新增工具

python 复制代码
# 忽略指定异常
from contextlib import suppress
with suppress(FileNotFoundError):
    os.remove('file.txt')

# 重定向 stdout
from contextlib import redirect_stdout
with redirect_stdout(f):
    help(pow)

4. pickle 协议 4(PEP 3154)

  • 支持任意嵌套数据
  • 更高效的字节码序列化
  • .pyc 文件体积更小

5. multiprocessing 新增启动方式

python 复制代码
import multiprocessing as mp

# 三种启动方式
mp.set_start_method('spawn')   # 类 Windows 方式(跨平台安全)
mp.set_start_method('forkserver')  # 更安全的 fork

ctx = mp.get_context('spawn')
pool = ctx.Pool(4)

6. hashlib 安全增强

python 复制代码
# PKCS#5 PBKDF2 密钥派生
import hashlib
hashlib.pbkdf2_hmac('sha256', password, salt, 100000)

7. ssl 安全增强

  • TLSv1.1 和 TLSv1.2 支持
  • 从 Windows 系统证书存储区读取证书
  • 服务端 SNI(Server Name Indication)支持
  • ssl.match_hostname() 主机名验证
  • SSLv3 默认禁用(3.4.2 之后)

8. dis 模块重构

python 复制代码
import dis

# 新增 Bytecode 和 Instruction 类
for instr in dis.get_instructions(lambda x: x + 1):
    print(instr.opname, instr.opcode)

# 栈效果分析
dis.stack_effect(opcode, arg)

9. inspect 改进

python 复制代码
# unwrap 解析 wrapper 链
inspect.unwrap(wrapped_func)

# signature() 支持更广泛的可调用对象
sig = inspect.signature(func)

10. 其他改进

python 复制代码
# min/max 支持 default 参数
min([])        # 报错
min([], default=None)  # 返回 None

# memoryview 注册为 Sequence,支持 reversed()
reversed(memoryview(b'hello'))

# html.unescape HTML5 实体解码
html.unescape('&lt;script&gt;')  # '<script>'

# base64 新增 Ascii85 和 Base85 编解码
base64.a85encode(data)  # 更高压缩率

# codecs.encode/decode 处理任意编解码器
from codecs import encode, decode
encode(b'hello', 'hex')   # b'68656c6c6f'
decode(b'68656c6c6f', 'hex')  # b'hello'

# __length_hint__() 正式成为语言规范(PEP 424)
# Frame.clear() 清除帧中所有局部变量引用

# gc.get_stats() 返回各代 GC 统计信息
gc.get_stats()

# glob.escape() 转义 glob 特殊字符
glob.escape('file[1].txt')  # 'file\\[1\\].txt'

三、运行时与实现改进

1. 对象安全销毁(PEP 442)

python 复制代码
# 3.3 及之前:__del__ 期间对象可能处于不一致状态
# 3.4+:__del__ 期间解释器状态一致,GC 更安全
class MyClass:
    def __del__(self):
        # 现在可以安全访问其他对象
        self.cleanup()

2. 可配置内存分配器(PEP 445)

python 复制代码
import sys
# 设置 Python 内存分配器
# PYTHONMALLOC=debug / malloc / mmap
sys.getallocated_blocks()  # 查看当前分配块数

3. 新文件描述符默认不可继承(PEP 446)

python 复制代码
import os
fd = os.open('file', os.O_RDONLY)
# 3.4+: 新文件描述符默认不可继承
# 可通过 os.set_inheritable(fd, True) 改为可继承

4. 模块规格类型(PEP 451)

python 复制代码
import importlib
# ModuleSpec 提供模块信息的统一封装
# 简化了导入系统的实现

5. Argument Clinic(PEP 436)

  • C 函数参数声明的 DSL
  • 自动生成参数解析代码和文档
  • 3.4+ 内置函数大量使用此工具

6. marshal 格式优化

  • 版本 3:更紧凑的序列化格式
  • interned 字符串只存储一份
  • .pyc 文件体积减小,内存占用降低

四、其他重要变化

改进 说明
abc.ABC 更简洁的抽象基类声明语法
模块可弱引用 weakref.ref(module) 可行
模块 __file__ 始终为绝对路径
dbm.open() 支持上下文管理器
doctest 支持 FAIL_FAST,支持扩展模块 __doc__
ipaddress 从临时 API 升级为稳定 API
html.parser strict 参数废弃
logging TimedRotatingFileHandler 支持 atTime
logging Unix 域套接字支持

总结

Python 3.4 的核心亮点:

  1. pip 默认安装(ensurepip)--- 终于开箱即用
  2. asyncio 模块 --- 异步 IO 框架的起点
  3. enum 枚举 --- 替换魔数常量的标准方案
  4. pathlib --- 面向对象路径操作
  5. statistics --- 基础统计内置
  6. tracemalloc --- 内存分配调试工具
  7. singledispatch --- 单分派泛型函数
  8. pickle 协议 4 --- 更高效的序列化
  9. TLS 安全增强 --- TLSv1.1/v1.2 默认支持
  10. 对象安全销毁 --- __del__ 更可靠

Python 3.4 是一个标准库大扩张的版本。虽然没有新的语法特性,但一口气新增了 asyncio、enum、pathlib、statistics、tracemalloc、selectors 六个重要模块,同时大幅改进了 pickle、ssl、functools、multiprocessing 等既有模块,为后续 Python 3 的异步生态和类型化发展奠定了坚实基础。


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

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

相关推荐
太阳上的雨天2 小时前
任何格式的文件转Markdown
python·ai
yaoxin5211232 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
weixin_468466853 小时前
纳米 AI 搜索新手极速上手指南
人工智能·python·深度学习·搜索引擎·ai·语言模型·自然语言处理
凯瑟琳.奥古斯特3 小时前
数据库原理选择题精选
数据库·python·职场和发展
彦为君3 小时前
JavaSE-07-异常机制
java·开发语言·后端·python·spring
适应规律4 小时前
【无标题】
人工智能·python·算法
XLYcmy4 小时前
全链路验证测试系统:一个针对智能代理(Agent)系统全链路能力的自动化验证脚本
分布式·python·http·网络安全·ai·llm·agent
有味道的男人4 小时前
电商效率翻倍:京东全量商品信息抓取
python