莫问 发表于 2015-12-15 10:43:05

Python functools之partial, update_wrapper, wraps

查看django的源码,看到这么一个函数:
def memoize(func, cache, num_args):
    """
    Wrap a function so that results for any argument tuple are stored in
    'cache'. Note that the args to the function must be usable as dictionary
    keys.

    Only the first num_args are considered when creating the key.
    """
    @wraps(func)
    def wrapper(*args):
      mem_args = args[:num_args]
      if mem_args in cache:
            return cache
      result = func(*args)
      cache = result
      return result
    return wrapper

经memoize包装过的函数可以对曾经的调用在内存建立缓存,提高性能,其中使用了wraps decorator,不明白其含义,赶紧打开手册,查阅一番,收获如下:

wraps主要是用来包装函数,使被包装含数更像原函数,它是对partial(update_wrapper, ...)的简单包装,
partial主要是用来修改函数签名,使一些参数固化,以提供一个更简单的函数供以后调用
update_wrapper是wraps的主要功能提供者,它负责考贝原函数的属性,默认是:'__module__', '__name__', '__doc__', '__dict__'。

所以@wraps的等价形式如下:
wrapper = partial(update_wrapper, wrapped=func, assigned=assigned, updated=updated)(wrapper)
进一步等价:
wrapper = update_wrapper(wrapper=wrapper, wrapped=func, assigned=assigned, updated=updated)

各个函数的详情说明请查看functools文档
页: [1]
查看完整版本: Python functools之partial, update_wrapper, wraps