每個函數只做一件事,並把這件事做好。
def process_order(user_id, items, payment_info, shipping_address, send_email=True):
# 1. 驗證用戶
# 2. 計算價格
# 3. 處理支付
# 4. 扣減庫存
# 5. 創建訂單
# 6. 發送郵件
# 7. 記錄日誌
# 8. 返回結果
pass # 200+ 行代碼...
def validate_user(user_id): ...
def calculate_total(items): ...
def process_payment(payment_info, amount): ...
def reserve_inventory(items): ...
def create_order(user_id, items, payment_result): ...
def send_confirmation_email(order): ...
def log_order_event(order, event): ...
def process_order(user_id, items, payment_info, shipping_address):
validate_user(user_id)
total = calculate_total(items)
payment_result = process_payment(payment_info, total)
reserve_inventory(items)
order = create_order(user_id, items, payment_result, shipping_address)
send_confirmation_email(order)
log_order_event(order, 'created')
return order
優勢:可測試、可復用、易閱讀、易修改、易組合。
# C++ 可能 20 行,Python 3 行
def parse_config(lines):
return {k.strip(): v.strip()
for line in lines
if '=' in line
for k, v in [line.split('=', 1)]}
# 全局狀態 — 並發災難、測試噩夢、隱式依賴
CACHE = {}
DB_CONN = None
def get_user(id):
global DB_CONN
if id in CACHE: return CACHE[id]
cursor = DB_CONN.cursor()
# ...
def get_user(user_id, db_conn, cache=None):
cache = cache or {}
if user_id in cache:
return cache[user_id]
cursor = db_conn.cursor()
# ...
return user
# 成功返回結果,失敗拋異常 (Python 風格)
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
# 多返回值用元組/命名元組/數據類
from collections import namedtuple
Result = namedtuple('Result', 'success data error')
def safe_divide(a, b):
try:
return Result(True, a/b, None)
except ZeroDivisionError as e:
return Result(False, None, str(e))
import timeit
GLOBAL = 5
def global_access():
return GLOBAL + 1
def local_access():
local = 5
return local + 1
# 測試
print(timeit.timeit(global_access, number=10_000_000)) # ~1.2s
print(timeit.timeit(local_access, number=10_000_000)) # ~0.8s
Python 變量查找順序:Local → Enclosing → Global → Builtin (LEGB),局部最快。
# ❌ 修改調用者傳入的列表
def bad_add_item(items, item):
items.append(item) # 副作用!
# ✅ 返回新列表 (函數式風格)
def good_add_item(items, item):
return items + [item]
# ✅ 或明確文檔並複製
def documented_add_item(items, item):
"""添加項目並返回新列表,不修改原列表"""
new_items = list(items) # 淺拷貝
new_items.append(item)
return new_items
# a.py
PI = 3.14
# b.py
import a
# ❌ 直接修改
a.PI = 3.14159 # 影響所有導入 a 的模塊!
# ✅ 提供設置函數
# a.py
def set_pi(value):
global PI
PI = value
# b.py
import a
a.set_pi(3.14159) # 明確意圖、可加驗證、可觀測
# 重構前:200行單體函數
def generate_report(data, config, output_path):
# 連接DB、查詢、計算、格式化、寫文件、發郵件、記錄日誌...
# 重構後:管道式組合
def generate_report(data, config, output_path):
validated = validate_input(data, config)
enriched = enrich_data(validated, db_conn)
calculated = calculate_metrics(enriched)
formatted = format_report(calculated, config.template)
write_file(formatted, output_path)
notify_stakeholders(formatted, config.recipients)
log_completion(output_path)
遵循這些原則,Python 代碼將具備優秀的可讀性、可測試性、可維護性與可擴展性。