关于functools模块的wraps装饰器用途
测试环境:Python3.6.2 + win10 + Pycharm2017.3
装饰器之functools模块的wraps的用途:
首先我们先写一个装饰器
# 探索functools模块wraps装饰器的用途
from functools import wraps def trace(func):
""" 装饰器 """ # @wraps(func)
def callf(*args, **kwargs):
""" A wrapper function """
print("Calling function:{}".format(func.__name__)) # Calling function:foo
res = func(*args, **kwargs)
print("Return value:{}".format(res)) # Return value:9
return res return callf @trace
def foo(x):
""" 返回给定数字的平方 """
return x * x if __name__ == '__main__':
print(foo(3)) #
print(foo.__doc__)
help(foo)
print(foo.__name__)
# print(foo.__globals__)
t = trace(foo)
print(t)
打印结果:
Calling function:foo
Return value:9
9
A wrapper function
Help on function callf in module __main__: callf(*args, **kwargs)
A wrapper function callf
<function trace.<locals>.callf at 0x0000022F744D8730>
不带wraps的装饰器示例
上面的装饰器例子等价于:trace(foo(3)),只是在使用装饰器时,我们不用再手动调用装饰器函数;
如果把这段代码提供给其他人调用, 他可能会想看下foo函数的帮助信息时:
>>>from xxx import foo
>>>help(foo) # print(foo__doc__)
Help on function callf in module __main__: callf(*args, **kwargs)
A wrapper function
这里,他可能会感到迷惑,继续敲:
>>> print(foo.__name__)
callf
最后, 他可能会看源码,找问题原因,我们知道Python中的对象都是"第一类"的,所以,trace函数会返回一个callf闭包函数,连带callf的上下文环境一并返回,所以,可以解释我们执行help(foo)的到结果了
那么,我们如果才能得到我们想要的foo的帮助信息呢,这里就要用到了functools的wraps了。
# 探索functools模块wraps装饰器的用途
from functools import wraps def trace(func):
""" 装饰器 """ @wraps(func)
def callf(*args, **kwargs):
""" A wrapper function """
print("Calling function:{}".format(func.__name__)) # Calling function:foo
res = func(*args, **kwargs)
print("Return value:{}".format(res)) # Return value:9
return res return callf @trace
def foo(x):
""" 返回给定数字的平方 """
return x * x if __name__ == '__main__':
print(foo(3)) #
print(foo.__doc__)
help(foo)
print(foo.__name__)
# print(foo.__globals__)
t = trace(foo)
print(t)
增加wraps的装饰器
至于wraps的原理,通过下面部分源码,可以自行研究,在此就不予展开扩展了
# 有关wraps的源码,有兴趣的可以自行研究下
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
'__annotations__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
# from the wrapped function when updating __dict__
wrapper.__wrapped__ = wrapped
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
class partial:
"""New function with partial application of the given arguments
and keywords.
"""
__slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
def __new__(*args, **keywords):
if not args:
raise TypeError("descriptor '__new__' of partial needs an argument")
if len(args) < 2:
raise TypeError("type 'partial' takes at least one argument")
cls, func, *args = args
if not callable(func):
raise TypeError("the first argument must be callable")
args = tuple(args)
if hasattr(func, "func"):
args = func.args + args
tmpkw = func.keywords.copy()
tmpkw.update(keywords)
keywords = tmpkw
del tmpkw
func = func.func
self = super(partial, cls).__new__(cls)
self.func = func
self.args = args
self.keywords = keywords
return self
def __call__(*args, **keywords):
if not args:
raise TypeError("descriptor '__call__' of partial needs an argument")
self, *args = args
newkeywords = self.keywords.copy()
newkeywords.update(keywords)
return self.func(*self.args, *args, **newkeywords)
@recursive_repr()
def __repr__(self):
qualname = type(self).__qualname__
args = [repr(self.func)]
args.extend(repr(x) for x in self.args)
args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items())
if type(self).__module__ == "functools":
return f"functools.{qualname}({', '.join(args)})"
return f"{qualname}({', '.join(args)})"
def __reduce__(self):
return type(self), (self.func,), (self.func, self.args,
self.keywords or None, self.__dict__ or None)
def __setstate__(self, state):
if not isinstance(state, tuple):
raise TypeError("argument to __setstate__ must be a tuple")
if len(state) != 4:
raise TypeError(f"expected 4 items in state, got {len(state)}")
func, args, kwds, namespace = state
if (not callable(func) or not isinstance(args, tuple) or
(kwds is not None and not isinstance(kwds, dict)) or
(namespace is not None and not isinstance(namespace, dict))):
raise TypeError("invalid partial state")
args = tuple(args) # just in case it's a subclass
if kwds is None:
kwds = {}
elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
kwds = dict(kwds)
if namespace is None:
namespace = {}
self.__dict__ = namespace
self.func = func
self.args = args
self.keywords = kwds
wraps源码示例
只要是知道,wraps是通过partial和update_wrapper来帮我们实现想要的结果的
摘自:
https://www.cnblogs.com/myd7349/p/how_to_use_wraps_of_functools.html # 关于functools模块的wraps装饰器
End
关于functools模块的wraps装饰器用途的更多相关文章
- 探究functools模块wraps装饰器的用途
<A Byte of Python>17.8节讲decorator的时候,用到了functools模块中的一个装饰器:wraps.因为之前没有接触过这个装饰器,所以特地研究了一下. 何谓“ ...
- wraps装饰器的作用
装饰器的本质是一个闭包函数,作用在于不改变原函数功能和调用方法的基础上给它添加额外的功能.装饰器在装饰一个函数时,原函数就成了一个新的函数,也就是说其属性会发生变化,所以为了不改变原函数的属性,我们会 ...
- python中functools.wraps装饰器的作用
functools.wraps装饰器用于显示被包裹的函数的名称 import functools def node(func): #@functools.wraps(func) def wrapped ...
- wraps装饰器的使用
functools模块中的wraps装饰器 说明 使用functools模块提供的wraps装饰器可以避免被装饰的函数的特殊属性被更改,如函数名称__name__被更改.如果不使用该装饰器,则会导致函 ...
- python学习笔记2-functools.wraps 装饰器
wraps其实没有实际的大用处, 就是用来解决装饰器导致的原函数名指向的函数 的属性发生变化的问题: 装饰器装饰过函数func, 此时func不是指向真正的func,而是指向装饰器中的装饰过的函数 i ...
- python functools.wraps装饰器模块
# -*-coding=utf-8 -*-#实现一个函数执行后计算执行时间的功能 __author__ = 'piay' import time, functools def foo(): ''' 定 ...
- python wraps装饰器
这是一个很有用的装饰器.看过前一篇反射的朋友应该知道,函数是有几个特殊属性比如函数名,在被装饰后,上例中的函数名foo会变成包装函数的名字 wrapper,如果你希望使用反射,可能会导致意外的结果.这 ...
- django的权限认证:登录和退出。auth模块和@login_required装饰器
在settings.py中配置LOGIN_URL参数: # 用户访问带有(@login_required)标签的页面(view)时,如果没有登录,就会跳转到LOGIN_URL(即登陆url). LOG ...
- Django内置auth模块中login_required装饰器用于类视图的优雅方式
使用多继承 以及类似java中的静态代理模式 原理:OrderView.as_view()根据广度优先,调用的是LoginRequiredMixin中的as_view(cls, *args, **kw ...
随机推荐
- 30-Python3 正则表达式
30-Python3 正则表达式 ''' re.match函数 ''' import re print(re.match('www','www.runoob.com').span()) print(r ...
- 将多行按分隔符"|"合成一行
原数据文件s.txt api_test account info 参数错误 合并后数据格式 api_test|account||参数错误||||| 方法介绍: 1.sed + xargs sed 's ...
- jquery dataTables例子
https://datatables.net/examples/styling/bootstrap.html http://datatables.club/example/#styling http: ...
- iOS UI调试神器,插件injection for Xcode使用方法
项目越来越大,代码编译时间越来越长,你是不是早已经厌倦了改一点点UI布局就要重新编译一次项目的过程,我们一分钟几百万上下的,怎能被编译浪费掉珍贵的时间.使用injectionforxcode这款插件, ...
- vue+element-ui中的表单验证(电话等等)
1. 2. 3. ============================================================上代码============================ ...
- 40.SEO----前端该懂的seo技巧
SEO要点:1.语义化html标签,用合适的标签嵌套合适的内容,不可过分依赖div,对浏览器更友善就能更容易被抓取.2.重要的内容html代码放在前面,放在左边.搜索引擎爬虫是从左往右,从上到下进行抓 ...
- vue中axios的封装
第一步还是先下载axios cnpm install axios -S 第二步建立一个htttp.js import axios from 'axios'; import { Message } fr ...
- ActiveMQ漏洞利用方法总结
转载来自:http://www.freebuf.com/column/161188.html 1.Console存在默认端口和默认密码/未授权访问(默认密码为admin:admin) ActiveMQ ...
- 注解(Annotation)
注解(Annotation)很重要,未来的开发模式都是基于注解的,JPA是基于注解的,Spring2.5以上都是基于注解的,Hibernate3.x以后也是基于注解的,现在的Struts2有一部分也是 ...
- arcgis api for javascript 添加图层时设置标注,自定义符号
<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <meta nam ...