Python 3.1 新特性全面总结
发布时间:2009 年 6 月 27 日
一、新语法特性
1. 自动编号字段 {}
python
# 3.1+:自动按顺序编号,无需手动写 {0} {1}
'Sir {} of {}'.format('Gallahad', 'Camelot')
# 等价于
'Sir {0} of {1}'.format('Gallahad', 'Camelot')
2. 多上下文管理器
python
# 3.1+:单个 with 语句多个管理器,无需嵌套
with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
for line in infile:
outfile.write(line)
# contextlib.nested() 废弃(不再需要)
3. round() 返回整数类型
python
# 3.1+:round(整数, n) 返回 int
round(1123, -2) # 1100(int,而非 float)
二、新增标准库
collections.OrderedDict --- 有序字典(PEP 372)
python
from collections import OrderedDict
# 记住插入顺序
d = OrderedDict([('banana', 3), ('apple', 4), ('pear', 1)])
list(d) # ['banana', 'apple', 'pear']
# 排序字典:按键排序
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
# 排序字典:按值排序
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
# 排序后删除再添加,新键追加到末尾,不维持排序
注:Python 3.7+ 普通
dict也保证插入顺序,但OrderedDict仍有move_to_end()、相等比较考虑顺序等独特功能。
collections.Counter --- 计数器
python
from collections import Counter
Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
# Counter({'blue': 3, 'red': 2, 'green': 1})
c = Counter(a=2, b=1, c=0, d=-2)
# 常用操作
+c # Counter({'a': 2, 'b': 1}) 移除计数 ≤ 0 的元素
-c # Counter({'d': 2}) 负数变正数
c.most_common(3) # 最常见的 3 个元素
c.elements() # 迭代器
tkinter.ttk --- 主题部件集
python
from tkinter import ttk
# 分离外观和行为,Tk 主题部件集
style = ttk.Style()
style.theme_use('clam')
ttk.Button(root, text='Click').pack()
importlib --- 导入系统纯 Python 参考实现
python
import importlib
# 提供 import 语句的纯 Python 实现
# 完整、可移植,定义了导入期间的所有行为
importlib.import_module('my_package.my_module')
logging.NullHandler --- 空日志处理器
python
import logging
# 库代码使用,抑制 "No handlers could be found" 警告
h = logging.NullHandler()
logging.getLogger('mylib').addHandler(h)
三、格式化改进
千分位分隔符(PEP 378)
python
format(1234567, ',d') # '1,234,567'
format(1234567.89, ',.2f') # '1,234,567.89'
format(1234567.89, ',f') # '1,234,567.890000'
format(12345.6 + 8901234.12j, ',f') # '12,345.6+8,901,234.12j'
浮点数 repr() 改进
python
# 3.0:repr(1.1) 返回冗长的 '1.1000000000000001'
# 3.1+:自动寻找最短等价表示 '1.1'
repr(1.1) # '1.1'(更简洁,值不变)
format(1.1, '.17g') # '1.1000000000000001'(旧算法仍可访问)
四、标准库重要改进
1. int.bit_length() --- 位数计算
python
>>> n = 37
>>> bin(37)
'0b100101'
>>> n.bit_length()
6
>>> (2**123 - 1).bit_length()
123
2. itertools 新增函数
python
# 组合(含重复)
>>> from itertools import combinations_with_replacement
>>> list(combinations_with_replacement('LOVE', 2))
['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']
# compress:按选择器过滤, 0 不要, 1 保留
>>> from itertools import compress
>>> list(compress(range(10), [0,0,1,1,0,1,0,1,0,0]))
[2, 3, 5, 7]
# count 支持 step 参数和任意序列
>>> from itertools import count
>>> c = count(start=0.5, step=0.25)
>>> [next(c) for _ in range(5)]
[0.5, 0.75, 1.0, 1.25, 1.5]
3. unittest 增强
python
class Tests(unittest.TestCase):
@unittest.skipUnless(sys.platform.startswith('win'), 'requires Windows')
def test_windows_feature(self): ...
@unittest.expectedFailure
def test_known_bug(self): ...
# assertRaises 作为上下文管理器
def test_division_by_zero(self):
with self.assertRaises(ZeroDivisionError):
x / 0
# 新增大量断言方法
self.assertSetEqual(set1, set2)
self.assertDictEqual(d1, d2)
self.assertListEqual(l1, l2)
self.assertSequenceEqual(s1, s2)
self.assertIsNone(obj)
self.assertIsNotNone(obj)
4. namedtuple rename 参数
python
from collections import namedtuple
# rename=True:自动将无效字段名改为 _0, _1 ...
# 用于外部数据源(CSV/SQL/用户输入)
UserQuery = namedtuple('UserQuery',
['region', 'dept', 'count(*)'], # 'count(*)' 无效
rename=True)
# UserQuery._fields = ('region', 'dept', '_2')
5. 其他改进
python
# gzip / bz2 支持上下文管理器
with gzip.GzipFile(filename, 'wb') as f:
f.write(b'data')
# Decimal.from_float() 精确转换
Decimal.from_float(1.1)
# Decimal('1.100000000000000088817841970012523233890533447265625')
# re.sub/re.split/re.subn 接受 flags 参数
re.sub(r'\d+', str, text, flags=re.IGNORECASE)
# functools.partial 可 pickle
import pickle
pickle.dumps(functools.partial(func, arg))
# sys.version_info 是 named tuple
sys.version_info.major # 3
sys.version_info.minor # 1
# io 新增常量
io.SEEK_SET # 0
io.SEEK_CUR # 1
io.SEEK_END # 2
# pickle 协议 2 自动处理 Python 2/3 兼容
pickle.dumps(s, protocol=2, fix_imports=True) # 自动映射 builtin -> builtins
# string.maketrans() 废弃
# 3.1+: bytes.maketrans() / bytearray.maketrans() / str.maketrans()
# runpy 支持包执行
# python -m mypackage 查找 __main__ 子模块
五、性能优化
| 优化 | 效果 |
|---|---|
| I/O 库 C 重写 | 提速 2-20 倍 |
--with-computed-goto |
字节码分发提速 20% |
| UTF-8/16/LATIN-1 解码 | 提速 2-4 倍 |
| GC 启发式 | 减少垃圾收集开销 |
| JSON C 扩展 | 大幅提速 |
| unpickle 属性名 intern | 减少内存占用 |
| 整数存储 30 位进制 | 64 位机器性能大幅提升 |
python
# sys.int_info 显示整数内部格式
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
# 64 位:30 位/数字;32 位:15 位/数字
总结
Python 3.1 的核心亮点:
OrderedDict--- 有序字典,记住插入顺序- 千分位分隔符
,---format(1234567, ',d')→'1,234,567' int.bit_length()--- 所需二进制位数- 自动编号字段
{}---format()简化 - 多上下文管理器 ---
with A() as a, B() as b:无需嵌套 Counter--- 便捷计数- 浮点数
repr()改进 --- 显示更简洁 itertools新函数 ---combinations_with_replacement、compressunittest.skip/expectedFailure--- 测试跳过和预期失败- I/O 库 C 重写 --- 性能提升 2-20 倍
Python 3.1 是一个性能大幅提升 + 实用工具增加 的版本。Python 3.0 的 I/O 库性能问题在 3.1 中得到彻底解决(C 重写),同时 OrderedDict、Counter 等新工具让常见编程模式更简洁。浮点数 repr() 的改进也解决了 3.0 时代用户最常抱怨的 "1.1 为什么显示成 1.1000000000000001" 问题。
参考:Python 3.1 官方文档 - What's New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。