Python3 中的 Functools

Functools

functools manual

functools 模块应用于高阶函数,即参数或/和返回值为其他函数的函数。 通常来说,此模块的功能适用于所有可调用对象。

cache

cached_property

cmp_to_key

lru_cache

一个装饰器,可以给函数提供缓存功能。

他有两个可选参数

  1. maxsize (default: 128)
    • 最多缓存maxsize组缓存
    • 如果设置为None,缓存可无限增长
  2. typed (deault: False)
    • 如果设置为True,则不同类型的函数参数将分别缓存。
    • 类型特异性仅适用于函数的直接参数而不是它们的内容。
from functools import lru_cache

@lru_cache
def calc(a: int , b : int) -> int:
    print("--calc--")
    return a + b

if __name__ == "__main__":
    print(calc(10,15))
    print(calc(10,15))
    print(calc(10,15))
    print(calc(10,15))

    print("--clear cache--")
    calc.cache_clear()

    print(calc(10,15))
    print(calc(20,30))
    print(calc(10,15))
    print(calc(20,30))

    print("--cache info--")
    print(calc.cache_info())

    print("--original function--")
    print(calc.__wrapped__(10,15))
    print(calc.__wrapped__(20,30))
    print(calc.__wrapped__(10,15))
    print(calc.__wrapped__(20,30))

注:

  • 通过 __wrapped__属性可以访问到原函数。

  • cache_clear 可以清除缓存。

  • cache_info 返回一个tuple(hits,misses, maxsize,currsize)

  • LRU函数前缀指的就是 Least Recently Used 算法。也就是说缓存数量大于maxsize时,将会清除最不常使用的缓存结果。

total_ordering

partial

partialmethod

reduce

这个函数会对参数序列中元素进行累积。用传给 reduce 中的第一个参数(是一个函数)先对集合中的第 12 个元素进行操作,得到的结果再与第三个数据用这个函数运算,最后得到一个结果。

这个函数大致等同于以下函数:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

示例:

from functools import reduce

i = [1,2,3,4,5]

def add(a,b):
    return a+b

print(reduce(add, i))

singledispatch

singledispatchmethod

update_wrapper

wraps

partial

func

args

keywords

qrcode

创建时间:2022-01-05 02:12:00

最后修改:2022-01-06 03:31:07