Python 3.3 新特性全面总结
发布时间:2012 年 9 月 29 日
一、新语法特性
1. yield from --- 生成器委托(PEP 380)
python
def accumulate():
tally = 0
while True:
next = yield
if next is None:
return tally
tally += next
def gather_tallies(tallies):
while True:
tally = yield from accumulate() # 委托给子生成器
tallies.append(tally)
acc = gather_tallies([])
next(acc)
for i in range(4):
acc.send(i)
acc.send(None) # 结束当前 tally
# tallies = [6]
yield from 还能正确传递 send() 和 throw(),是协程的基础。
2. u"unicode" 语法恢复(PEP 414)
python
# 3.3+:恢复 u 前缀,与 Python 2 兼容
s = u"你好世界"
3. 异常上下文抑制(PEP 409)
python
class D:
def __getattr__(self, attr):
try:
return self._extra[attr]
except KeyError:
raise AttributeError(attr) from None # 抑制原始上下文
D({}).x
# 仅显示 AttributeError,不再显示 KeyError 上下文链
4. __qualname__ 属性(PEP 3155)
python
class C:
def meth(self): pass
C.meth.__qualname__ # 'C.meth'
C.meth.__name__ # 'meth'
def outer():
def inner(): pass
return inner
outer().__qualname__ # 'outer.<locals>.inner'
二、新增标准库模块
venv --- 虚拟环境(PEP 405)
bash
# 命令行创建虚拟环境
pyvenv myenv
# 或 Python 3.3 起
python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
faulthandler --- 底层崩溃调试
python
import faulthandler
faulthandler.enable() # SIGSEGV/SIGFPE 时自动打印 traceback
# 或启动时
python -X faulthandler script.py
ipaddress --- IP 地址处理(PEP 3144)
python
import ipaddress
ip = ipaddress.ip_address('192.168.1.1')
ip.version # 4
net = ipaddress.ip_network('192.168.1.0/24')
list(net) # 所有 IP
ipaddress.ip_address('2001:db8::1') # IPv6
lzma --- LZMA/XZ 压缩
python
import lzma
with lzma.open('data.xz', 'w') as f:
f.write(b'hello world')
with lzma.open('data.xz', 'r') as f:
print(f.read())
unittest.mock --- Mock 对象(正式加入标准库)
python
from unittest.mock import Mock, patch
m = Mock()
m.method(1, 2, key='value')
m.method.assert_called_with(1, 2, key='value')
# 模拟模块函数
with patch('os.getcwd', return_value='/fake/path'):
print(os.getcwd())
三、重大架构改进
1. 灵活的 Unicode 表示(PEP 393)
根据字符串内容自动选择最优编码:
| 内容 | 存储 |
|---|---|
| 纯 ASCII | 1 字节/字符 |
| BMP(U+0000-U+FFFF) | 2 字节/字符 |
| 非 BMP | 4 字节/字符 |
python
# sys.maxunicode 永远为 0x10FFFF
import sys
sys.maxunicode # 1114111
# 窄构建已废除,所有平台行为统一
len('\U0010FFFF') # 1(而非 2)
'\U0010FFFF'[0] # '\U0010FFFF'(而非高代理项)
2. OS/IO 异常层次重构(PEP 3151)
python
# 3.2 写法(需导入 errno)
from errno import ENOENT
try:
open('missing.txt')
except IOError as err:
if err.errno == ENOENT: ...
# 3.3+ 简洁写法
try:
open('missing.txt')
except FileNotFoundError: # OSError 的子类
print("文件不存在")
except PermissionError:
print("权限不足")
except TimeoutError:
print("超时")
except BrokenPipeError: # ConnectionError 的子类
print("管道断裂")
OSError 子类一览:
BlockingIOError/ChildProcessError/ConnectionErrorFileExistsError/FileNotFoundErrorInterruptedError/IsADirectoryError/NotADirectoryErrorPermissionError/ProcessLookupError/TimeoutError
3. import 机制重写(importlib)
__import__由 importlib 实现,所有 Python 实现统一sys.meta_path和sys.path_hooks显式暴露- 所有模块有
__loader__和__package__属性 - 更细粒度的模块锁(避免全局锁死锁)
4. Key-Sharing 字典(PEP 412)
同一类的多个实例共享键存储,减少内存占用:
python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# 大量实例时,键名只存储一份
5. sys.implementation(PEP 421)
python
import sys
sys.implementation
# namespace(name='cpython', version=Version(3, 3, 0),
# hexversion=505948320, cache_tag='cpython-33')
# 新增 types.SimpleNamespace
from types import SimpleNamespace
ns = SimpleNamespace(x=1, y=2)
ns.z = 3
del ns.x
四、标准库重要改进
1. decimal 模块 C 实现 --- 提速 10-120 倍
python
from decimal import Decimal
# C 模块整合 libmpdec,性能提升 10-120 倍
Decimal('3.1415926535') ** Decimal('2')
2. inspect.signature() --- 函数签名对象(PEP 362)
python
import inspect
def greet(name: str, greeting: str = "Hello") -> str:
pass
sig = inspect.signature(greet)
# Signature(parameters=[
# Parameter('name', PARAMETER_KEYWORD_ONLY, annotation=str),
# Parameter('greeting', PARAMETER_KEYWORD_ONLY, default='Hello', annotation=str)
# ])
sig.parameters['name'].annotation # <class 'str'>
3. open() 增强
python
# 'x' 模式:独占创建(文件存在则报错)
with open('new.txt', 'x') as f: # 等价于 O_CREAT | O_EXCL
f.write('data')
# opener 参数:自定义文件描述符
import os
fd = os.open('file', os.O_WRONLY | os.O_CLOEXEC)
open(fd, 'w', closefd=False)
4. print() flush 参数
python
print("Loading...", flush=True, end='')
5. str.casefold() --- 大小写折叠
python
# casefold 比 lower() 更彻底,用于大小写不敏感比较
'ß'.casefold() # 'ss'(lower() 返回 'ß')
'FINTE'.casefold() # 'finte'
6. hmac.compare_digest() --- 防时序攻击比较
python
import hmac
# 用于防止通过比较时间推断密码前缀
hmac.compare_digest(a, b) # 常数时间比较
7. contextlib.ExitStack --- 上下文管理器栈
python
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(f)) for f in filenames]
# 自动全部清理,无需嵌套 with
8. collections.ChainMap --- 链式映射
python
from collections import ChainMap
defaults = {'theme': 'default', 'lang': 'en'}
user_prefs = {'lang': 'zh'}
config = ChainMap(user_prefs, defaults)
config['lang'] # 'zh'(先查 user_prefs)
config['theme'] # 'default'(回退到 defaults)
9. datetime 改进
python
# timestamp():datetime 转 POSIX 时间戳
import datetime
dt = datetime.datetime.now()
dt.timestamp() # 1381234567.123
# 无参数 astimezone()
dt.astimezone() # 转换到系统时区
# naive 和 aware datetime 比较返回 False(不再抛 TypeError)
10. bz2 完全重写
python
import bz2
# 支持任意文件类对象
bz2.open('file.bz2', 'wt')
# 多流解压缩(pbzip2 格式)
# 追加模式
11. 其他改进
python
# hash 随机化默认启用
# PYTHONHASHSEED 环境变量控制种子
# list/bytearray 新增 copy() 和 clear()
lst = [1, 2, 3]
lst.copy()
lst.clear()
# bytes 范围方法接受 0-255 整数
b'hello'.count(0) # 字节 0 出现次数
# bytes/bytearray 新增 rjust/ljust/center 支持 bytearray 填充
# raw bytes 字面量 rb"..." 和 br"..." 均可用
# dict.setdefault 原子单次查找
# range() 相等性比较
# abc 移到 collections.abc
from collections.abc import Mapping, MutableSequence
# Counter 支持 + - | & 一元/位运算
from collections import Counter
c = Counter(a=1, b=2)
+c # Counter({'a': 1, 'b': 2})
-c # Counter({'b': 2, 'a': 1})(移除负数计数)
# crypt.mksalt() --- 生成安全盐值
import crypt
crypt.mksalt()
五、Windows 改进
py.exe 启动器(PEP 397)
python
# 脚本 shebang 行指定版本
#!/usr/bin/env python3
#!/usr/bin/python3.3
# 命令行指定版本
py -3 # 使用 Python 3
py -3.3 # 使用 Python 3.3
py -2.7 # 使用 Python 2.7
六、安全改进
- Hash 随机化默认启用 --- 防止 DoS 哈希冲突攻击
hmac.compare_digest()--- 防时序攻击- 更细粒度的导入锁 --- 避免多线程导入死锁
总结
Python 3.3 的核心亮点:
yield from--- 生成器委托,彻底简化协程和生成器链- 虚拟环境(venv) --- 内置支持,无需 virtualenv
- 隐式命名空间包(PEP 420) --- 目录可无
__init__.py - 灵活 Unicode 表示 --- 内存减少 2-3 倍,跨平台一致
py.exeWindows 启动器 --- 多版本共存下的版本选择- OS/IO 异常层次重构 ---
FileNotFoundError等语义化异常 raise ... from None--- 干净的异常链控制__qualname__--- 更精确的函数/类路径信息inspect.signature()--- 完整的函数签名内省decimalC 实现 --- 性能提升 10-120 倍
Python 3.3 是一个深度重构 的版本。它不仅解决了 Python 3 早期遗留的兼容性问题(恢复 u"" 语法),还在 Unicode 存储、异常层次、导入机制、内存占用等底层基础设施上做了大量重构。特别是 yield from 的引入为后来 asyncio 的完善奠定了关键基础,而虚拟环境的内置支持则让 Python 环境的隔离管理终于标准化。
参考:Python 3.3 官方文档 - What's New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。