【问题标题】:@wraps() not behaving isn't returning the original functions values@wraps() 不正常不返回原始函数值
【发布时间】:2019-10-13 04:57:50
【问题描述】:

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

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.

【问题讨论】:

  • 你应该在函数f上调用__name__print(f"The function {f.__name__} completed in {end-start} seconds.")
  • 有效,但我想知道为什么考虑到@wraps 装饰器,这甚至是必要的。我之前在 python2.7 中以这种方式实现了它,没有问题,也不需要说 f.__name__

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


【解决方案1】:

你应该在函数f上调用__name__

print(f"The function {f.__name__} completed in {end-start} seconds.")

原因是__name__,默认指的是封闭函数;我不认为@wraps 会覆盖这种行为;它无法知道您要打印的确切内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多