returning values from decorated functions in python

Viewed 2049

I have the following decorated function:

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))

When I run calculate_sum() I get Calling calculate_sum: 0.00043 which is the output of the @logging_time.

How can I also retrieve the return value of the calculate_sum function as well ? Why isnt the sum(range(10000)) returned as well ?

2 Answers

Simply save result where you call the function and return it

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))

just store the return value and return it

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())

Result:

Calling calculate_sum: 0.00012
49995000
Related