从python装饰函数返回值

问题描述

我具有以下修饰功能

import time
def logging_time(func):
    """Decorator that logs time"""
    def logger():
        """Function that logs time"""
        start = time.time()
        func()
        print(f"Calling {func.__name__}: {time.time() - start:.5f}")

    return logger
     
@logging_time
def calculate_sum():
     return sum(range(10000))

运行calculate_sum()时,我得到Calling calculate_sum: 0.00043,它是@logging_time输出

我还如何还检索return函数calculate_sum值?为什么sum(range(10000))也不返回?

解决方法

只需将结果保存在调用函数的位置并返回

import time
def logging_time(func):
    """Decorator that logs time"""
    def logger():
        """Function that logs time"""
        start = time.time()
        result = func()  # save result here
        print(f"Calling {func.__name__}: {time.time() - start:.5f}")
        return result  # return it here

    return logger
     
@logging_time
def calculate_sum():
     return sum(range(10000))
,

只需存储返回值并返回

import time
def logging_time(func):
    """Decorator that logs time"""
    def logger():
        """Function that logs time"""
        start = time.time()
        result = func()
        print(f"Calling {func.__name__}: {time.time() - start:.5f}")
        return result
    return logger
     
@logging_time
def calculate_sum():
     return sum(range(10000))

print(calculate_sum())

结果:

Calling calculate_sum: 0.00012
49995000