functools — 可调用对象的高阶函数和操作

源代码: Lib/functools.py


The functools 模块用于高阶函数:充当 (或返回) 其它函数的函数。一般而言,任何可调用对象都可以视为用于此模块用途的函数。

The functools 模块定义了下列函数:

@ functools. cache ( user_function )

简单轻量的无界函数缓存。有时称为 “memoize” .

返回如同 lru_cache(maxsize=None) ,创建查找函数自变量的字典的瘦包裹器。因为从不需要驱逐旧值,这更小且更快相比 lru_cache() 带尺寸限制。

例如:

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1
>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600