Python中8种Functools使用方法

在本文中,我们来看看functools 标准库模块以及您可以用它做的 6 件很酷的事情

1. 缓存
可以使用@cache装饰器(以前称为@lru_cache)作为“简单的轻量级无界函数缓存”。
典型的例子是计算斐波那契数列,其中缓存中间结果,显着加快计算速度:

from functools import cache

@cache
def fibonacci(n: int) -> int:
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

for i in range(40):
    print(fibonacci(i))


由于所有重复计算,它需要 28.30 秒 ,使用@cache后,只需要 0.02 秒

可以使用 @cached_property来对属性执行相同的操作

2.编写更少的注释方法
使用 @total_ordering 装饰器,您可以编写 __eq__() 和 __lt__()、__le__()、__gt__() 或 __ge__()中的一个,因此只需两个,而且它会自动为您提供其他方法。代码少,自动化程度高。

根据文档,它的代价是更慢的执行速度和更复杂的堆栈跟踪。此外,该装饰器不会覆盖类或其超类中已声明的方法。

"dunder "一词来源于 "双下划线"。在 Python 中,"dunder 方法 "也被称为 "魔法方法 "或 "特殊方法",是一组预定义的方法,其名称的开头和结尾都带有双下划线 (如 __init__, __str__) 。

3.冻结函数
partial() 可以对现有函数进行基本封装,这样就可以在没有默认值的地方设置默认值。

例如,如果我想让 print() 函数总是以逗号而不是换行符结束,我可以使用 partial() 如下:

from functools import partial
print_no_newline = partial(print, end=', ')

# Normal print() behavior:
for _ in range(3): print('test')
test
test
test

# My new frozen print() one:
for _ in range(3): print_no_newline('test')
test, test, test,


另一个例子是通过将 exp 参数固定为 2,将 pow() 内建函数冻结为总是平方:

from functools import partial

# Using partial with the built-in pow function
square = partial(pow, exp=2)

# Testing the new function
print(square(4)) # Outputs: 16
print(square(5)) # Outputs: 25

另外一个例子:

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(square(4))  # 16
print(cube(4))    # 64


通过使用 partial(),可以简化重复调用,提高代码清晰度,并创建具有预设配置的可重用组件。

还有 partialmethod(),其行为类似 partial(),但旨在用作方法定义而非直接调用。

4.使用泛型函数
随着 PEP 443的引入,Python 增加了对 "单调度泛型函数 "的支持。

这些函数允许您为一个主函数定义一组函数(变体),其中每个变体处理不同类型的参数。

@singledispatch 装饰器协调了这种行为,使函数能够根据参数的类型改变其行为。

from functools import singledispatch

@singledispatch
def process(data):
    """Default behavior for unrecognized types."""
    print(f
"Received data: {data}")

@process.register(str)
def _(data):
   
"""Handle string objects."""
    print(f
"Processing a string: {data}")

@process.register(int)
def _(data):
   
"""Handle integer objects."""
    print(f
"Processing an integer: {data}")

@process.register(list)
def _(data):
   
"""Handle list objects."""
    print(f
"Processing a list of length: {len(data)}")

# Testing the generic function
process(42)        # Outputs: Processing an integer: 42
process(
"hello")   # Outputs: Processing a string: hello
process([1, 2, 3]) # Outputs: Processing a list of length: 3
process(2.5)       # Outputs: Received data: 2.5

在上面的示例中,当我们调用流程函数时,会根据传递的参数类型调用相应的注册函数。

对于没有注册函数的数据类型,则使用默认行为(在主 @singledispatch 装饰函数下定义)。

这样的设计可以使代码更有条理、更清晰,尤其是当一个函数需要以不同方式处理各种数据类型时。

5.帮助编写更好的装饰器
在创建装饰器时,使用 functools.wraps 保留原始函数的元数据(如名称和 docstring)是一种很好的做法。这样可以确保被装饰的函数保持其特性。

在 Python 中编写装饰器时,最好使用 functools.wraps() 以避免丢失所装饰函数的 docstring 和其他元数据:

from functools import wraps


def mydecorator(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        result = func(*args, **kwargs)
        return result

    return wrapped


@mydecorator
def hello(name: str):
    """Print a salute message"""
    print(f
"Hello {name}")


多亏了 functools,封装元数据才得以保留:
print(hello.__doc__)  # 'Print a salute message'
print(hello.__annotations__)  # {'name': <class 'str'>}

# 如果没有 functools.wraps 就会打印:
print(hello.__doc__)  # None
print(hello.__annotations__)  # {}

这样保留装饰函数的元数据,开发人员就更容易理解函数的目的和用法。

6.汇总数据或累积转换
functools.reduce(func, iterable) 是一个函数,它通过对可迭代元素从左到右依次应用一个函数来累加结果。

注意 reduce() 在 Python 3 中被移到了 functools 模块中,而在 Python 2 中 reduce() 是一个内置函数。

这在各种需要汇总数据或以累积方式转换数据的场景中都很有用。

下面是一个例子,我用它来聚合对数字列表的运算符模块操作:

from functools import reduce
import operator

numbers = list(range(1, 11))  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(operator.add(1, 2))  # 3

print(reduce(operator.add, numbers))  # 55
print(reduce(operator.sub, numbers))  # -53
print(reduce(operator.mul, numbers))  # 3628800
print(reduce(operator.truediv, numbers))  # 2.7557319223985893e-07

7、使用 functools.timeout 为函数执行超时:
您可以使用 functools.timeout 为函数设置最长执行时间。如果函数没有在指定时间内执行完毕,则会引发超时错误(TimeoutError)。

from functools import timeout

@timeout(5)
def slow_function():
    # Some time-consuming operations
    import time
    time.sleep(10)
    return "Function completed successfully"

try:
    result = slow_function()
    print(result)
except TimeoutError:
    print(
"Function took too long to execute")


8、使用 functools.singleton 创建单例 (Python 3.11+):
从 Python 3.11 开始,functools 模块包含了 singleton,它是一个装饰器,可以确保一个类只有一个实例。

from functools import singleton

@singleton
class MySingletonClass:
    def __init__(self):
        print("Creating instance")

obj1 = MySingletonClass()
obj2 = MySingletonClass()

print(obj1 is obj2)  # Output: True


这些示例只是 Python 中 functools 模块众多功能中的一小部分。它是函数式编程的强大工具,可以简化代码的设计和维护。