Python中为何建议在decorator函数中使用functo

2019-03-02  本文已影响0人  小餐包

以最常见的time_it装饰器函数为例, 如下代码中:

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

关于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.

上一篇 下一篇

猜你喜欢

热点阅读