一、格式化输出
reprlib 模块
- 提供定制版 repr(),缩略显示大型或深层嵌套对象
import reprlib
reprlib.repr(set('supercalifragilisticexpialidocious'))
# "{'a', 'c', 'd', 'e', 'f', 'g', ...}"
pprint 模块
- 美化输出,添加换行和缩进显示复杂数据结构
import pprint
t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
pprint.pprint(t, width=30)
textwrap 模块
- 格式化文本段落适应屏幕宽度
import textwrap
doc = """长文本..."""
print(textwrap.fill(doc, width=40))
locale 模块
- 处理地域文化相关的数据格式
import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')
x = 1234567.8
locale.format_string("%d", x, grouping=True) # '1,234,567'
二、模板
string.Template 类
- 简化模板语法,支持占位符替换
from string import Template
t = Template('${village}folk send $$10 to $cause.')
t.substitute(village='Nottingham', cause='ditch fund')
- safe_substitute():缺失数据时保留原占位符
t.safe_substitute(d) # 不会抛出KeyError
- 自定义分隔符:创建Template子类
class BatchRename(Template):delimiter = '%'
三、使用二进制数据记录格式
struct 模块
- 处理不定长度的二进制记录格式
import struct
with open('myfile.zip', 'rb') as f:data = f.read()
fields = struct.unpack('<IIIHH', data[start:start+16])
# 小端字节序,无符号整数
四、多线程
threading 模块
- 实现后台任务运行
import threading, zipfileclass AsyncZip(threading.Thread):def run(self):# 压缩操作print('Finished background zip')background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
background.join() # 等待线程结束
-
同步原语:线程锁、事件、条件变量、信号量
-
推荐使用 queue:集中资源请求,更易设计
五、日志记录
logging 模块
- 灵活的日志记录系统
import logging
logging.debug('Debug info')
logging.info('Info message')
logging.warning('Warning: %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error')
-
日志级别:DEBUG, INFO, WARNING, ERROR, CRITICAL
-
输出选项:文件、邮件、套接字、HTTP服务器等
六、弱引用
weakref 模块
- 跟踪对象而不创建永久引用
import weakref, gcclass A:def __init__(self, value):self.value = valuea = A(10)
d = weakref.WeakValueDictionary()
d['primary'] = a # 不创建强引用
del a
gc.collect()
d['primary'] # KeyError: 对象已被回收
七、用于操作列表的工具
array 模块
- 类型一致、存储密度高的数组
from array import array
a = array('H', [4000, 10, 700, 22222]) # 双字节无符号整数
sum(a) # 26932
collections.deque
- 高效的双端队列
from collections import deque
d = deque(["task1", "task2", "task3"])
d.append("task4")
d.popleft() # "task1"
bisect 模块
- 操作有序列表
import bisect
scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua')]
bisect.insort(scores, (300, 'ruby'))
heapq 模块
- 堆队列算法
from heapq import heapify, heappop, heappush
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data)
heappush(data, -5)
[heappop(data) for i in range(3)] # [-5, 0, 1]
八、十进制浮点运算
decimal 模块
- 精确的十进制浮点运算
from decimal import *
round(Decimal('0.70') * Decimal('1.05'), 2) # Decimal('0.74')
round(.70 * 1.05, 2) # 0.73(二进制浮点不精确)
-
适用场景:
-
财务应用
-
需要精确十进制表示
-
控制精度和四舍五入
-
跟踪有效小数位
-
精确性优势:
-
Decimal('1.00') % Decimal('.10') # Decimal('0.00')
sum([Decimal('0.1')]*10) == Decimal('1.0') # True
- 精度控制:
getcontext().prec = 36 # 设置精度
Decimal(1) / Decimal(7) # 36位小数