'Is there a way to get function output in decorators?

This is my code:

def decorator(func):
    def _(*args, **kwargs):
        print(args, kwargs, func)

        result = func(*args, **kwargs) # function result

        print("Result value is {}".format(result))
    
    return _

@decorator
def function(a: int, b: int) -> int:
    return a + b

print(function(2, 2))

In decorator, i'm trying to get the result value, but in order to do it, i need to call the function twice. Is there a way to get the result value in decorator immediately, without calling the function twice? Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source