一、格式化輸出
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位小數