以最常見的time_it裝飾器函數(shù)為例龙优, 如下代碼中:
第一個time_it函數(shù)沒有使用functools.wraps, 功能上這個裝飾器并沒有什么問題站绪;
第二個better_time_it在wrapper函數(shù)面前又加了一個@functools.wraps(func)函數(shù)阀参, 其他代碼一致鸣皂;
import time
import functools
def time_it(func):
def wrapper(*args, **kwargs):
"""This is docs for wrapper"""
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print('Running "%s" in %.3f seconds' % (func.__name__, (end - start)))
return result
return wrapper
def better_time_it(func):
@functools.wraps(func) # Pay attention here!
def wrapper(*args, **kwargs):
"""This is docs for wrapper"""
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print('Running "%s" in %.3f seconds' % (func.__name__, (end - start)))
return result
return wrapper
我們的測試代碼如下:
@time_it
def foo():
"""This is docs foo function"""
print('Foo!')
@better_time_it
def yeah():
"""This is docs yeah function"""
print('Yeah!')
if __name__ == '__main__':
help(foo)
help(yeah)
這里我用help函數(shù)查看function的doc strings摔踱,得到如下結(jié)果:
Help on function wrapper in module __main__:
wrapper(*args, **kwargs)
This is docs for wrapper
Help on function yeah in module __main__:
yeah()
This is docs yeah function
可以看到使用time_it的foo函數(shù)的docs變成了wrapper函數(shù)的docs虐先;
而使用better_time_it的yeah函數(shù)的docs才是我們期望得到的實際docs;
不止help函數(shù)的結(jié)果會有變化派敷,因為使用裝飾器實際上返回的并不是原函數(shù)本身蛹批,所以原函數(shù)相關(guān)的metadata信息已經(jīng)變化了,如果不使用functools.wraps函數(shù)就會導(dǎo)致此類副作用,比如序列化和debugger時也會使結(jié)果混亂般眉,所以養(yǎng)成良好的習(xí)慣了赵,自定義decorator的時應(yīng)該盡量使用functools.wraps
關(guān)于functools.wraps()函數(shù)的官方文檔中寫道:
The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful.