以最常見的time_it裝飾器函數為例, 如下代碼中:
第一個time_it函數沒有使用functools.wraps, 功能上這個裝飾器并沒有什么問題;
第二個better_time_it在wrapper函數面前又加了一個@functools.wraps(func)函數, 其他代碼一致;
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函數查看function的doc strings,得到如下結果:
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函數的docs變成了wrapper函數的docs;
而使用better_time_it的yeah函數的docs才是我們期望得到的實際docs;
不止help函數的結果會有變化,因為使用裝飾器實際上返回的并不是原函數本身,所以原函數相關的metadata信息已經變化了,如果不使用functools.wraps函數就會導致此類副作用,比如序列化和debugger時也會使結果混亂,所以養成良好的習慣,自定義decorator的時應該盡量使用functools.wraps
關于functools.wraps()函數的官方文檔中寫道:
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.