一个已经存在 10 年,却被严重低估的库!
The following article is from Python编程时光 Author 写代码的明哥
【CSDN 编者按】decorator,你知道它的存在吗?一个编写 python 装饰器代码的库,它好像慢慢淡出了我们的视线。如果你想提高装饰器编码效率,decorator或许是你不错的选择。
今天介绍的是一个已经存在十三年,但是依旧不红的库 decorator,好像很少有人知道他的存在一样。
这个库可以帮你做什么呢 ?
其实很简单,就是可以帮你更方便地写 python 装饰器代码,更重要的是,它让 Python 中被装饰器装饰后的方法长得更像装饰前的方法。
本篇文章不会过多的向你介绍装饰器的基本知识,我会默认你知道什么是装饰器,并且懂得如何写一个简单的装饰器。
不了解装饰器的可以先去阅读我之前写的文章,非常全且详细的介绍了装饰器的各种实现方法。
常规的装饰器
下面这是一个最简单的装饰器示例,在运行 myfunc 函数的前后都会打印一条日志。
def deco(func):
def wrapper(*args, **kw):
print("Ready to run task")
func(*args, **kw)
print("Successful to run task")
return wrapper
@deco
def myfunc():
print("Running the task")
myfunc()
使用神库
$ python3 -m pip install decorator
from decorator import decorator
@decorator
def deco(func, *args, **kw):
print("Ready to run task")
func(*args, **kw)
print("Successful to run task")
@deco
def myfunc():
print("Running the task")
myfunc()
带参数的装饰器可用?
def decorator(func):
def wrapper(*args, **kw):
func(*args, **kw)
return wrapper
第二种:带参数,这就相对复杂了,理解起来了也不是那么容易。
def decorator(arg1, arg2):
def wrapper(func):
def deco(*args, **kwargs)
func(*args, **kwargs)
return deco
return wrapper
from decorator import decorator
@decorator
def warn_slow(func, timelimit=60, *args, **kw):
t0 = time.time()
result = func(*args, **kw)
dt = time.time() - t0
if dt > timelimit:
logging.warn('%s took %d seconds', func.__name__, dt)
else:
logging.info('%s took %d seconds', func.__name__, dt)
return result
@warn_slow(timelimit=600) # warn if it takes more than 10 minutes
def run_calculation(tempdir, outdir):
pass
装饰函数的第一个参数,还是被装饰器 func ,这个跟之前一样
而第二个参数 timelimit 写成了位置参数的写法,并且有默认值
再往后,就还是跟原来一样使用了可变参数的写法
签名问题有解决?
def wrapper(func):
def inner_function():
pass
return inner_function
@wrapper
def wrapped():
pass
print(wrapped.__name__)
#inner_function
为什么会这样子?不是应该返回 func 吗?
这也不难理解,因为上边执行func 和下边 decorator(func) 是等价的,所以上面 func.__name__ 是等价于下面decorator(func).__name__ 的,那当然名字是 inner_function
def wrapper(func):
def inner_function():
pass
return inner_function
def wrapped():
pass
print(wrapper(wrapped).__name__)
#inner_function
目前,我们可以看到当一个函数被装饰器装饰过后,它的签名信息会发生变化(譬如上面看到的函数名)
那如何避免这种情况的产生?
解决方案就是使用我们前面所说的 functools .wraps 装饰器。
它的作用就是将 被修饰的函数(wrapped) 的一些属性值赋值给 修饰器函数(wrapper) ,最终让属性的显示更符合我们的直觉。
from functools import wraps
def wrapper(func):
@wraps(func)
def inner_function():
pass
return inner_function
@wrapper
def wrapped():
pass
print(wrapped.__name__)
# wrapped
那么问题就来了,我们使用了 decorator 之后,是否还会存在这种签名的问题呢?
写个例子来验证一下就知道啦
from decorator import decorator
@decorator
def deco(func, *args, **kw):
print("Ready to run task")
func(*args, **kw)
print("Successful to run task")
@deco
def myfunc():
print("Running the task")
print(myfunc.__name__)
输出的结果是 myfunc,说明 decorator 已经默认帮我们处理了一切可预见的问题。
总结一下
decorator 是一个提高装饰器编码效率的第三方库,它适用于对装饰器原理感到困惑的新手,可以让你很轻易的写出更符合人类直觉的代码。
对于带参数装饰器的定义,是非常复杂的,它需要要写多层的嵌套函数,并且需要你熟悉各个参数的传递路径,才能保证你写出来的装饰器可以正常使用。
这时候,只要用上 decorator 这个库,你就可以很轻松的写出一个带参数的装饰器。同时你也不用担心他会出现签名问题,这些它都为你妥善的处理好了。
这么棒的一个库,推荐你使用起来。