萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python functools 模組核心功能全解析

functools 是 Python 標準庫中專為高階函數、可呼叫物件操作設計的工具箱。本文詳細解析六大核心功能:partial、wraps/update_wrapper、reduce、cmp_to_key、total_ordering、lru_cache (補充),附完整範例與應用場景。

1. functools.partial:凍結參數、建立新可呼叫物件

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 屬性,可內省。
  • 常用於回呼函數預設參數、API 客戶端預設 headers/timeout、事件處理器綁定上下文。

2. functools.wraps / update_wrapper:修正裝飾器元資料遺失

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__',)

3. functools.reduce:函數式歸約 (Python 3 移至 functools)

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)

4. functools.cmp_to_key:舊式比較函數轉 key 函數

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 排序

5. functools.total_ordering:自動補全比較魔術方法

類別只需定義 __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__

6. 補充:functools.lru_cache:備忘錄模式快取

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_keycmp 轉 keycmp_func
total_ordering自動補全比較方法cls (需定義 __eq__ + 一個比較)
lru_cache函數結果快取maxsize, typed

善用 functools,能寫出更函數式、更可複用、更易維護的 Python 程式碼。

copyright © 萬盛學電腦網 all rights reserved