python@wraps实现原理
@wraps作用
python中的装饰器装饰过的函数其实就不是函数本身了,我们可以看看下面的例子
import time
def timmer(func):
"""timmer doc"""
def inner(*args, **kwargs):
"""inner doc"""
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print("函数运行时间为 %s" % (end - start))
return res
return inner @timmer
def func_test():
"""func_test doc"""
time.sleep(2)
return print(func_test.__name__) # inner
print(func_test.__doc__) # inner doc
按我们正常的思维,func_test.__name__应该拿到的就是“func_test”,所以这个结果就印证了上面的第一句话,但是这是我们加一个@wraps,就会发现好像一切都正常了:
import time
from functools import wraps
def timmer(func):
"""timmer doc"""
@wraps(func)
def inner(*args, **kwargs):
"""inner doc"""
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print("函数运行时间为 %s" % (end - start))
return res
return inner @timmer
def func_test():
"""func_test doc"""
time.sleep(2)
return print(func_test.__name__) # func_test
print(func_test.__doc__) # func_test doc
@wraps的实现原理
为了方便理解,我把源码和例子放在了一起,这样的话我们看着会方便:
import time
from functools import partial WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
'__annotations__')
WRAPPER_UPDATES = ('__dict__',) def update_wrapper(wrapper, # inner
wrapped, # func_test
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)
"""
print('update_wrapper 执行...')
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()
print('update_wrapper 执行结束')
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().
"""
print('wraps 执行...')
print('wraps 执行结束') # 纯粹为了打印出来的结果好理解
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated) def timmer(func):
print('timmer 执行...') @wraps(func) # inner = update_wrapper的返回值
def inner(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print("函数运行时间为 %s" % (end - start))
return res print('timmer 执行结束') # 当然不是真正的结束,执行完下一行才结束
return inner @timmer
def func_test():
print("func_test 执行...")
time.sleep(2)
print("func_test 运行结束")
return func_test() """
打印结果如下:
timmer 执行...
wraps 执行...
wraps 执行结束
update_wrapper 执行...
update_wrapper 执行结束
timmer 执行结束
func_test 执行...
func_test 运行结束
函数运行时间为 2.0000197887420654 从打印的结果我们可以看出,@语法会在函数定义或者说模块初始化阶段(可能称呼不对,以后回来改)就执行了
"""
上面的例子中我加了很多打印,主要是为了提醒一下在func_test()函数执行之前,@语法已经执行了。
其实原理很简单,用了一个偏函数,去执行update_wrapper,真正起作用的也是这个函数,func_test执行之前,update_wrapper函数就会把inner函数的好多属性(示例中WRAPPER_ASSIGNMENTS,WRAPPER_UPDATES指向的属性 ,还有__wrapped__属性)全部其换成func_test的属性。
python@wraps实现原理的更多相关文章
- Python分布式爬虫原理
转载 permike 原文 Python分布式爬虫原理 首先,我们先来看看,如果是人正常的行为,是如何获取网页内容的. (1)打开浏览器,输入URL,打开源网页 (2)选取我们想要的内容,包括标题,作 ...
- Python Socket通信原理
[Python之旅]第五篇(一):Python Socket通信原理 python Socket 通信理论 socket例子 摘要: 只要和网络服务涉及的,就离不开Socket以及Socket编 ...
- python解释执行原理(转载)
Python解释执行原理 转自:http://l62s.iteye.com/blog/1481421 这里的解释执行是相对于编译执行而言的.我们都知道,使用C/C++之类的编译性语言编写的程序,是需要 ...
- python虚拟机运行原理
近期为了面试想要了解下python的运行原理方面的东西,奈何关于python没有找到一本类似于深入理解Java虚拟机方面的书籍,找到了一本<python源码剖析>电子书,但是觉得相对来说最 ...
- python程序执行原理
Python程序的执行原理 1. 过程概述 Python先把代码(.py文件)编译成字节码,交给字节码虚拟机,然后解释器一条一条执行字节码指令,从而完成程序的执行. 1.1python先把代码(.py ...
- Python进阶----索引原理,mysql常见的索引,索引的使用,索引的优化,不能命中索引的情况,explain执行计划,慢查询和慢日志, 多表联查优化
Python进阶----索引原理,mysql常见的索引,索引的使用,索引的优化,不能命中索引的情况,explain执行计划,慢查询和慢日志, 多表联查优化 一丶索引原理 什么是索引: 索引 ...
- Hive Python Streaming的原理及写法
在Hive中,须要实现Hive中的函数无法实现的功能时,就能够用Streaming来实现. 其原理能够理解成:用HQL语句之外的语言,如Python.Shell来实现这些功能,同一时候配合HQL语句, ...
- 轻松搞懂Python递归函数的原理与应用
递归: 在函数的定义中,函数内部的语句调用函数本身. 1.递归的原理 学习任何计算机语言过程中,“递归”一直是所有人心中的疼.不知你是否听过这个冷笑话:“一个面包,走着走着饿了,于是就把自己吃了”. ...
- 5分钟看懂系列:Python 线程池原理及实现
概述 传统多线程方案会使用"即时创建, 即时销毁"的策略.尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数极其频繁,那么服务器 ...
随机推荐
- 数据结构——Java实现顺序栈
一.分析 栈是限定仅在表的一端进行插入或删除操作的线性表,对于栈来说,操作端称为栈顶,另一端则称为栈底,栈的修改是按照后进先出的原则进行的,因此又称为后进先出的线性表. 顺序栈是指利用顺序存储结构实现 ...
- PHP面向对象和面向过程
编程界不论是PHP.Python都有这么两种编程思想,oop面向对象.pop面向过程,这两种在功能上没有多大区别,但是在代码编写上却有很大区别.今天就记录一下面向对象和面向过程的优点.缺点.定义.实现 ...
- Dynamics CRM项目实例之十:CRM 2015的捆绑销售在订单中的效果
关注本人微信和易信公众号: 微软动态CRM专家罗勇,回复141或者20150122可方便获取本文,同时可以在第一时间得到我发布的最新的博文信息,follow me! 上一篇博文我在素格格新 ...
- 为什么 User 应该翻译为 「使用权人」 ?
User, 旧译「用户」,我在此向大家倡议有条件地选择翻译为「使用权人」. 1. __使用权人__更能反应 User 的本质特征 我们看到一匹马的时候不会说这是一头猪,而 User 的本质是什么?在我 ...
- Go语言打造以太坊智能合约测试框架(level2)
传送门: 柏链项目学院 第二课 智能合约自动化编译 前期内容回顾 之前我们的介绍的是如何通过solc编译智能合约,并且调用智能合约,本节我们继续实践,将智能合约的代码自动化编译以及abi文件生成搞定. ...
- clamwin + 拖拽查毒+右键查毒
下载 clamwin 到 windows 并安装 http://www.clamwin.com/ 为了方便使用clamwin,写一个bat,实现拖拽到bat 自动查毒 @echo off mode c ...
- 解决 WordPress“正在执行例行维护,请一分钟后回来”
WordPress在升级程序.主题.插件时,都会先切换到维护模式,也就是显示 “正在执行例行维护,请一分钟后回来(Briefly unavailable for scheduled maintenan ...
- python 中 try catch finally语句中含有return语句的执行情况
无论是在try还是在except中,遇到return时,只要设定了finally语句,就会中断当前的return语句,跳转到finally中执行,如果finally中遇到return语句,就直接返回, ...
- cordova 自定义 plugin
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/qq_30879415/article/details/81265455准备工作安装cordovanp ...
- Core官方DI解析(3)-ServiceCallSite.md
上一篇说过在整个DI框架中IServiceProviderEngine是核心,但是如果直接看IServiceProviderEngine派生类其实看不出也没什么东西,因为这个类型其实都是调用的其它对象 ...