@wraps()行为不正常,不返回原始函数值

时间:2019-05-27 15:43:27

标签: python-3.x python-decorators functools

我写了一个相当基本的装饰器:

def test_speed(f, *args, **kwargs):
    """This decorator will print out the time taken for input function to run."""

    @wraps(f)
    def wrapper():
        """Wrapper function returned by the outer function."""
        start = time.time()
        to_return = f(*args, **kwargs)
        end = time.time()
        print(f"The function {__name__} completed in {end-start} seconds.")

        return to_return
    return wrapper

在一个名为工具的项目中的名为装饰器的python脚本中。我已将该项目添加到配置中的第二个项目中,该项目用于练习使用多处理模块。我编写了一些测试函数来检查某些循环的多处理速度:

""" A script to practice using multiprocessing effectively in python."""

from decorators import *
from multiprocessing import *


def _loop(i, process_number):
    for i in range(i):
        if i % 500 == 0:
            print(f'{i} iterations of loop {process_number}.')


def serial_looping():

    _loop(10000, 'one')
    _loop(10000, 'two')
    _loop(10000, 'three')


@test_speed
def parallel_looping():
    loop_one = Process(target=_loop, args=(10000, 'one'))
    loop_two = Process(target=_loop, args=(10000, 'two'))
    loop_three = Process(target=_loop, args=(10000, 'three'))


if __name__ == '__main__':
    serial_looping()
    parallel_looping()

def serial_looping():

    _loop(10000, 'one')
    _loop(10000, 'two')
    _loop(10000, 'three')


@test_speed
def parallel_looping():
    loops = []
    loops.append(Process(target=_loop, args=(10000, 'one')))
    loops.append(Process(target=_loop, args=(10000, 'two')))
    loops.append(Process(target=_loop, args=(10000, 'three')))
    for loop in loops:
        loop.start()
        print('loop')


if __name__ == '__main__':
    serial_looping()
    parallel_looping()

我的问题是,当调用包装函数时,它代替名称来说明包装器的项目名称,装饰器,如下所示:

The function decorators completed in 5.841255187988281e-05 seconds.

当然这应该显示为: The function serial_looping completed in 5.841255187988281e-05 seconds.

1 个答案:

答案 0 :(得分:1)

您应该在函数f上调用print(f"The function {f.__name__} completed in {end-start} seconds.")

__name__

原因是@wraps在默认情况下指的是封闭函数;我不认为some_data-a会覆盖此行为;它不知道您打算打印什么。