python wrapper_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[mem_args]

result = func(*args)

cache[mem_args] = 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文档

阅读(6031) | 评论(0) | 转发(1) |

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值