Python 3.3 新特性全面总结

Python 3.3 新特性全面总结

发布时间:2012 年 9 月 29 日

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


一、新语法特性

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 / ConnectionError
  • FileExistsError / FileNotFoundError
  • InterruptedError / IsADirectoryError / NotADirectoryError
  • PermissionError / ProcessLookupError / TimeoutError

3. import 机制重写(importlib)

  • __import__ 由 importlib 实现,所有 Python 实现统一
  • sys.meta_pathsys.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 的核心亮点:

  1. yield from --- 生成器委托,彻底简化协程和生成器链
  2. 虚拟环境(venv) --- 内置支持,无需 virtualenv
  3. 隐式命名空间包(PEP 420) --- 目录可无 __init__.py
  4. 灵活 Unicode 表示 --- 内存减少 2-3 倍,跨平台一致
  5. py.exe Windows 启动器 --- 多版本共存下的版本选择
  6. OS/IO 异常层次重构 --- FileNotFoundError 等语义化异常
  7. raise ... from None --- 干净的异常链控制
  8. __qualname__ --- 更精确的函数/类路径信息
  9. inspect.signature() --- 完整的函数签名内省
  10. decimal C 实现 --- 性能提升 10-120 倍

Python 3.3 是一个深度重构 的版本。它不仅解决了 Python 3 早期遗留的兼容性问题(恢复 u"" 语法),还在 Unicode 存储、异常层次、导入机制、内存占用等底层基础设施上做了大量重构。特别是 yield from 的引入为后来 asyncio 的完善奠定了关键基础,而虚拟环境的内置支持则让 Python 环境的隔离管理终于标准化。


参考:Python 3.3 官方文档 - What's New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。

相关推荐
EntyIU10 小时前
创建FastAPI项目步骤
网络·python·fastapi
隔壁大炮10 小时前
MNE-Python 第4天学习笔记:数据预处理(一)—— 滤波与重参考
python·eeg·mne·脑电数据处理
深度先生10 小时前
pip 与包管理基础——你的第一个包管理工具
python
biter down11 小时前
6:控件操作与鼠标模拟
开发语言·python
沉下去,苦磨练!11 小时前
python的数据分析Pandas
python·数据分析·pandas
import_random11 小时前
[python]numpy.arange()函数的使用
python
aqi0011 小时前
15天学会AI应用开发(五)使用AI摘要来压缩上下文消息
人工智能·python·大模型·ai编程·ai应用
叶梓翎11 小时前
AI语义搜索本地素材一键整合包官方下载
人工智能·python·图搜索
敲代码的小王!11 小时前
Python 核心语法 —— 数据、流程与容器
开发语言·python