Python 3.2 新特性全面总结
发布时间:2011 年 2 月 13 日
一、重大 PEP 特性
1. argparse --- 命令行解析模块(PEP 389)
python
import argparse
parser = argparse.ArgumentParser(description='Manage servers')
parser.add_argument('action', choices=['deploy', 'start', 'stop'])
parser.add_argument('targets', nargs='+', metavar='HOSTNAME')
parser.add_argument('-u', '--user', required=True)
# 支持子命令
subparsers = parser.add_subparsers()
deploy_parser = subparsers.add_parser('deploy')
deploy_parser.add_argument('--force')
2. concurrent.futures --- 并发执行框架(PEP 3148)
python
import concurrent.futures
import shutil
# 线程池并行复制文件
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
for src, dst in zip(src_files, dst_files):
e.submit(shutil.copy, src, dst)
# 进程池 CPU 密集任务
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as e:
results = list(e.map(heavy_task, items))
3. __pycache__ 字节码目录(PEP 3147)
python
import collections
collections.__cached__
# 'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
import imp
imp.get_tag() # 'cpython-32'
imp.cache_from_source('file.py') # '__pycache__/file.cpython-32.pyc'
4. 稳定 ABI(PEP 384)
c
// 扩展模块使用 Py_LIMITED_API 可跨版本兼容
#define Py_LIMITED_API
#include <Python.h>
5. WSGI v1.0.1(PEP 3333)
python
# WSGI now correctly handles bytes/text separation in Python 3
# Headers: native str (Latin-1)
# Body: bytes
# start_response() uses native strings
二、标准库新增模块
logging.config.dictConfig() --- 字典日志配置(PEP 391)
python
import logging.config
config = {
"version": 1,
"formatters": {"brief": {"format": "%(levelname)-8s: %(message)s"}},
"handlers": {"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout"
}},
"root": {"level": "DEBUG", "handlers": ["console"]}
}
logging.config.dictConfig(config)
logging.info("Hello") # 自动配置,无需手动 handler
三、标准库重要改进
1. functools.lru_cache() --- LRU 缓存
python
import functools
@functools.lru_cache(maxsize=128)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
# 跟踪缓存状态
fib.cache_info()
# CacheInfo(hits=196, misses=14, maxsize=128, currsize=14)
fib.cache_clear() # 清空缓存
# @wraps 保留被包装函数引用
@functools.wraps(original_func)
def wrapper(*args, **kwargs):
return original_func(*args, **kwargs)
wrapper.__wrapped__ # 原始函数
2. functools.total_ordering --- 自动填充比较方法
python
@functools.total_ordering
class Student:
def __eq__(self, other): return ...
def __lt__(self, other): return ...
# 自动生成 __le__, __gt__, __ge__
3. itertools.accumulate() --- 累积求和
python
from itertools import accumulate
list(accumulate([8, 2, 50])) # [8, 10, 60]
list(accumulate([0.1, 0.4, 0.2, 0.3])) # [0.1, 0.5, 0.7, 1.0]
4. collections.OrderedDict.move_to_end() --- 有序字典重排序
python
from collections import OrderedDict
d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
d.move_to_end('X') # 移动到最后
d.move_to_end('a', last=False) # 移动到最前
# 访问频率重排序(LRU 模式)
d[k] = d.pop(k) # 更新访问时间
5. threading.Barrier --- 线程同步栅栏
python
from threading import Barrier, Thread
all_ready = Barrier(len(sites))
def process(site):
data = fetch(site)
all_ready.wait() # 等待所有站点都完成
merge(data)
for site in sites:
Thread(target=process, args=(site,)).start()
6. datetime.timezone --- 时区支持
python
from datetime import datetime, timezone
# 创建带时区的 datetime
dt = datetime(2020, 1, 1, 12, 0, tzinfo=timezone.utc)
datetime.now(timezone.utc) # 当前 UTC 时间
# strptime 支持 %z
datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
7. math 模块新增函数
python
import math
math.isfinite(x) # True for regular numbers, False for NaN/Inf
math.expm1(x) # e**x - 1(对小 x 更精确)
math.erf(x) # 误差函数
math.erfc(x) # 互补误差函数 1 - erf(x)
math.gamma(x) # 伽马函数
math.lgamma(x) # log(gamma(x))(避免大数溢出)
8. str.format_map() --- 任意映射格式化
python
from collections import defaultdict
d = defaultdict(lambda: 'unknown', {'name': 'Alice'})
"Hello {name}".format_map(d) # 'Hello Alice'
# 支持 __missing__ 的自定义 dict
class PlaceholderDict(dict):
def __missing__(self, key):
return f'<{key}>'
9. 其他改进
python
# range 支持 index() 和 count()(Sequence 完整实现)
range(0, 100, 2).index(10) # 5
range(0, 100, 2).count(10) # 1
# str() 现在等于 repr()(消除混淆)
str(3.14159) # '3.14159'(不再 '3.14')
# memoryview 支持 release() 和上下文管理器
with memoryview(b'abcdefgh') as v:
print(v.tolist())
# format() 的 # 标志可用于浮点数
format(12.34, '#5.0f') # ' 12.'(强制显示小数点)
# callable() 复活
callable(max) # True
callable(20) # False
# functools.wraps 添加 __wrapped__ 属性
# __wrapped__ 可用于恢复原始函数、取消缓存等
# io.BytesIO.getbuffer() --- 无复制的缓冲区视图
buffer = byte_stream.getbuffer()
buffer[start:end] = new_data # 就地编辑
# csv 新增 unix_dialect 和 writeheader()
csv.DictWriter(sys.stdout, fields).writeheader()
# logging 新增 style 参数
basicConfig(style='{', format="{name} {message}")
basicConfig(style='$', format="$name $message")
# reprlib.recursive_repr() 装饰器
@recursive_repr()
def __repr__(self):
return '<' + '|'.join(map(repr, self)) + '>'
# collections.deque 新增 count() 和 reverse()
# ResourceWarning 新增(未关闭文件等资源警告)
# 默认静默,可通过 -Wdefault 启用
四、运行时改进
| 改进 | 说明 |
|---|---|
hasattr() 更严格 |
只捕获 AttributeError,不再掩盖其他异常 |
局部变量 del |
允许删除嵌套块中的自由变量 |
| C 结构体支持 named tuple | os.stat() / time.gmtime() 可索引切片 |
| 非 ASCII 路径 | import 支持非 ASCII 用户名目录 |
-q 静默模式 |
启动时不显示版本信息 |
PYTHONWARNINGS |
环境变量控制警告,更灵活 |
五、安全与兼容性
- ResourceWarning:未关闭文件、资源泄漏发出警告
- WSGI v1.0.1:明确 bytes/text 分离规范,修复 Python 3 兼容性
- email/mailbox/nntplib:全面修复 Python 3 bytes/text 模型问题
总结
Python 3.2 的核心亮点:
argparse模块 --- 取代 optparse,支持位置参数、子命令、必需选项concurrent.futures--- ThreadPoolExecutor/ProcessPoolExecutor,并发编程标准化__pycache__目录 --- 多 Python 版本字节码共存,告别.pyc冲突functools.lru_cache()--- 便捷的函数结果缓存functools.total_ordering--- 自动填充比较运算符itertools.accumulate()--- 累积计算threading.Barrier--- 多线程同步栅栏datetime.timezone--- 标准时区支持math扩展 --- isfinite、expm1、erf、gamma 等科学计算函数logging.config.dictConfig()--- 字典配置日志,灵活可编程
Python 3.2 是一个工程质量 提升的版本。它没有语言层面的重大语法变化,但通过 concurrent.futures、argparse、lru_cache、logging.dictConfig 等大量实用工具的引入,大幅提升了标准库的可用性和编程效率。特别是 __pycache__ 目录的引入解决了多 Python 版本共存的长期痛点,而 concurrent.futures 则为 Python 3.2 时代的高并发编程奠定了基础。
参考:Python 3.2 官方文档 - What's New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。