functools 是 Python 標準庫中專為高階函數、可呼叫物件操作設計的工具箱。本文詳細解析六大核心功能:partial、wraps/update_wrapper、reduce、cmp_to_key、total_ordering、lru_cache (補充),附完整範例與應用場景。
from functools import partial
def add(a, b):
return a + b
add3 = partial(add, 3) # 凍結第一個參數為 3
add5 = partial(add, 5)
print(add3(4)) # 7
print(add5(10)) # 15
# 關鍵字參數也可凍結
int_base2 = partial(int, base=2)
print(int_base2('1010')) # 10
partial 物件保留 func, args, keywords 屬性,可內省。from functools import wraps, update_wrapper
# 手動 update_wrapper
def my_decorator(func):
def wrapper(*args, **kwargs):
print("before")
return func(*args, **kwargs)
return update_wrapper(wrapper, func) # 複製 __name__, __doc__, __module__, __dict__
# 裝飾器寫法 (推薦)
def my_decorator2(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("before")
return func(*args, **kwargs)
return wrapper
@my_decorator2
def hello():
"""Say hello"""
print("Hello")
print(hello.__name__) # 'hello'
print(hello.__doc__) # 'Say hello'
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
from functools import reduce
# 累加
reduce(lambda x, y: x + y, [1,2,3,4,5]) # 15
# 等同 sum([1,2,3,4,5])
# 字串連接
reduce(lambda x, y: x + y, ['a','b','c']) # 'abc'
# 提供初始值
reduce(lambda x, y: x * y, [1,2,3], 10) # 60 (10*1*2*3)
Python 3 移除 cmp 參數,sorted() 等只接受 key。cmp_to_key 將 cmp(a,b) -> -1/0/1 轉為 key(x) -> sortable_object。
from functools import cmp_to_key
import locale
# 區域感知排序
words = ['apple', 'Äpfel', 'banana']
sorted(words, key=cmp_to_key(locale.strcoll))
# 正確處理德語 Umlaut 排序
類別只需定義 __eq__ + 任一 __lt__, __le__, __gt__, __ge__,裝飾器自動生成其餘方法。
from functools import total_ordering
@total_ordering
class Student:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def __eq__(self, other):
return (self.lastname.lower(), self.firstname.lower()) == \
(other.lastname.lower(), other.firstname.lower())
def __lt__(self, other):
return (self.lastname.lower(), self.firstname.lower()) < \
(other.lastname.lower(), other.firstname.lower())
students = [Student('John', 'Doe'), Student('Jane', 'Smith')]
print(sorted(students)) # 自動支援 <, <=, >, >=, ==, !=
print(dir(Student)) # 含 __le__, __gt__, __ge__
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
print(fib(100)) # 瞬間回傳,避免指數爆炸
print(fib.cache_info()) # CacheInfo(hits=98, misses=101, maxsize=128, currsize=101)
| 功能 | 用途 | 關鍵參數 |
|---|---|---|
| partial | 凍結參數建立新函數 | func, *args, **keywords |
| wraps | 裝飾器保留元資料 | wrapped, assigned, updated |
| reduce | 歸約運算 | function, iterable[, initializer] |
| cmp_to_key | cmp 轉 key | cmp_func |
| total_ordering | 自動補全比較方法 | cls (需定義 __eq__ + 一個比較) |
| lru_cache | 函數結果快取 | maxsize, typed |
善用 functools,能寫出更函數式、更可複用、更易維護的 Python 程式碼。