Python 動態型別靈活便利,但也帶來隱患:函數預期 str 卻收到 bytes、預期 int 卻傳入 float,測試覆蓋不足時極易上線爆炸。本文示範用 裝飾器 實現輕量級運行時型別檢查,兼顧安全與開發效率。
@accepts(int, str, float) 宣告參數型別debug=0 關閉、1 警告、2 拋異常__name__、__doc__)import sys
from functools import wraps
from typing import Tuple, Type, Any
NONE, WARN, STRONG = 0, 1, 2
def accepts(*expected_types: Type, debug: int = WARN):
"""
參數型別檢查裝飾器
:param expected_types: 依參數順序預期的型別
:param debug: 0=關閉, 1=stderr警告, 2=拋出TypeError
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if debug == NONE:
return func(*args, **kwargs)
# 僅檢查位置參數(關鍵字參數略過,保持靈活)
if len(args) != len(expected_types):
msg = (f"'{func.__name__}' expects {len(expected_types)} positional args, "
f"got {len(args)}")
_report(msg, debug)
return func(*args, **kwargs) if debug == WARN else (_ for _ in ()).throw(TypeError(msg))
actual_types = tuple(type(arg) for arg in args)
if actual_types != expected_types:
exp_str = ', '.join(t.__name__ for t in expected_types)
act_str = ', '.join(t.__name__ for t in actual_types)
msg = (f"'{func.__name__}' accepts ({exp_str}), but was given ({act_str})")
_report(msg, debug)
return func(*args, **kwargs)
return wrapper
return decorator
def _report(msg: str, level: int):
if level == WARN:
print(f"TypeWarning: {msg}", file=sys.stderr)
elif level == STRONG:
raise TypeError(msg)
# === 使用範例 ===
@accepts(int, int, int, debug=STRONG)
def average(x, y, z):
return (x + y + z) / 3
@accepts(str, int, debug=WARN)
def greet(name, age):
print(f"Hello {name}, age {age}")
if __name__ == '__main__':
print(average(1, 2, 3)) # 2.0
# average(1.5, 2, 3) # TypeError
greet("Alice", 30) # 正常
greet("Bob", "thirty") # TypeWarning on stderr
typing.Union、Optional、Any,配合 isinstance 判斷。@returns(type) 裝飾器。inspect.signature 讀取 __annotations__,免除重複宣告。debug=NONE,零開銷;或用 mypy 靜態檢查取代運行時檢查。裝飾器型別檢查不是靜態型別系統的替代品,但在「漸進式型別」策略下,它能以極低成本攔截大量低級錯誤。配合 mypy 靜態分析、pydantic 資料驗證,構建多層防禦,讓 Python 專案更健壯。