functools模块学习

2022-10-08,,

目录

  • 3. update_wrapper(wrapper, warpped, assigned=wrapper_assignmedts, updated=wrapper_updates)
  • 4. wraps(wrapped, assigned=wrapper_assignments, updasted=wrapper_updates)
  • 8. lru_cache(user_function) / lru_cache(maxsize=128, typed=false)

1. partial(func, /, *args, **kwargs)

  • 封装原函数并返回一个partial object对象, 可直接调用
  • 固定原函数的部分参数, 相当于为原函数添加了固定的默认值
    相当于如下代码:
def partial(func, /, *args, **kwargs):
    def newfunc(*fargs, **fkwargs):
        newkwargs = {**kwargs, **fkwargs}
        return func(*args, *fargs, **newkwargs)
    newfunc.func = func
    newfunc.args = args
    newfunc.kwargs = kwargs
    return newfunc

例如, 需要一个默认转换二进制的int()函数:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'convert base 2 string to an int.'
>>> basetwo('10010')
18

2. partialmethod(func, /, *args, **kwargs)

  • partial用法相同, 专门用于类定义中(由于类定义中第一个参数默认需要self/cls, 所以partial不适用)
  • 在类中, 不论普通方法, staticmethod, classmethod还是abstractmethod都适用

例如:

class cell:
    def __init__(self):
        self._alive = false
    
    @property
    def alive(self):
        return self._alive
    
    def set_alive(self, state):
        self._alive = bool(state)
    set_alive = partialmethod(set_state, true)
    set_dead = partialmethod(set_state, false)

>>> c = cell()
>>> c.alive
false
>>> c.set_alive()
>>> c.alive
true

3. update_wrapper(wrapper, warpped, assigned=wrapper_assignmedts, updated=wrapper_updates)

  • 更新装饰函数(wrapper), 使其看起来更像被装饰函数(wrapped)
  • 主要用在装饰器中, 包裹被装饰函数, 并返回一个更新后的装饰函数. 如果装饰函数没有更新, 那么返回的函数的元数据将来自装饰器, 而不是原始函数
  • 两个可选参数用来指定原始函数的哪些属性直接赋值给装饰函数, 哪些属性需要装饰函数做相应的更新. 默认值是模块级常量wrapper_assignments(赋值装饰函数的__module__, __name__, __qualname__, __annotations____doc__属性)和wrapper_updated(更新装饰函数的__dict__属性)

4. wraps(wrapped, assigned=wrapper_assignments, updasted=wrapper_updates)

  • 简化调用update_wrapper的过程, 作为装饰器使用
  • 相当于partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)

例如:

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print('calling decorated function')
        return f(*args, **kwargs)
    return wrapper

@my_decorator
def example():
    """docstring"""
    print('called example function')

>>> example()
calling decorated function
called example function
>>> example.__name__
'example'
>>> example.__doc__
'docstring'

如果没有使用wraps, 那么被装饰函数的名字将会是wrapper, 而且原始函数example的文档字符串将会丢失.

5. singledispatch(func)

  • 作为装饰器使用, 将被装饰函数转换为一个泛函数(generic function)
  • 根据第一个参数的类型分派执行不同的操作

例如:

@singledispatch
def fun(arg, verbose=false):
    if verbose:
        print('let me just say,', end='')
    print(arg)

@fun.register(int)
def _(arg, verbose=false):
    if verbose:
        print('strength in numbers, eh?', end='')
    print(arg)

@fun.register(list)
def _(arg, verbose=false)
    if verbose:
        print('enumerate this: ')
    for i, elem in enumerate(arg):
        print(i, elem)


>>> fun('hello world')
hello world
>>> fun('test', verbose=true)
let me just say, test
>>> fun(123, verbose=true)
strength in numbers, eh? 123
>>> fun(['issac', 'chaplin', 'mr bean'], verbose=true)
enumerate this:
0 issac
1 chaplin
2 mr bean

可以使用"函数类型注释"替代上面显式指定类型

@fun.register
def _(arg: int, verbose=false):
    pass

6. singledispatchmethod(func)

  • 将方法装饰为泛函数
  • 根据第一个非self或非cls参数的类型分派执行不同的操作
  • 可以与其他装饰器嵌套使用, 但singledispatchmethod,dispatcher.register必须在最外层
  • 其他用法与singledispatch相同

例如:

class negator:
    @singledispatchmethod
    @classmethod
    def neg(cls, arg):
        raise notimplementederror("cannot negate a")
    
    @neg.register
    @classmethod
    def _(cls, arg: int):
        return -arg
    
    @neg.register
    @classmethod
    def _(cls, arg: bool):
        return not arg

7. cached_property(func)

  • 将方法转换为一个属性, 与@property相似
  • 被装饰的方法仅计算一次, 之后作为普通实例属性被缓存
  • 要求实例拥有可变的__dict__属性(在元类或声明的__slots__中未包含__dict__的类中不可用)

例如:

class dataset:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers
    
    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
    
    @cached_property
    def variance(self):
        return statistics.variance(self._data)

cached_property的底层是一个非数据描述符, 在func第一次计算时, 将结果保存在实例的一个同名属性中(实例的__dict__中), 由于实例属性的优先级大于非数据描述符, 之后的所有调用只直接取实例属性而不会再次计算

8. lru_cache(user_function) / lru_cache(maxsize=128, typed=false)

  • 缓存被装饰函数的最近maxsize次的调用结果
  • maxsize如果设置为none, lru缓存机制将不可用, 缓存会无限增长.maxsize的值最好是2的n次幂
  • 由于底层使用字典缓存结果, 所以被装饰函数的参数必须可哈希.
  • 不同的参数模式会分开缓存为不用的条目, 例如f(a=1, b=2)f(b=2, a=1)就会作为两次缓存
  • 如果typed设置为true, 不同类型的函数参数将会被分开缓存, 例如f(3)f(3.0)

例如:

@lru_cache(maxsize=none)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> fib.cache_info()
cacheinfo(hits=28, misses=16, maxsize=none, currsize=16)

《functools模块学习.doc》

下载本文的Word格式文档,以方便收藏与打印。