Search code examples
python-3.xreturndecorator

python decorator to print return values


This question concerns Python 3. Is there a way to make a decorator print the return values to any function? This question Decorator to print function call details - parameters names and effective values will print all the values you pass to a function. Is there a way to make a decorator that prints the values of whatever the function returns regardless of whether it returns a single value or many?

So that if you were to run this:

multiply(subtract(add(1,2),add(3,4)),9)

with all of the functions decorated with @superecho it would log:

function call add() 1,2
function add() returns 3
function call add() 3,4
function add() returns 7
function call subtract() 3 7
function subtract() returns -4
function call multiply() -4 9
function multiply() returns -36

Solution

  • import functools
    
    def monitor_results(func):
        @functools.wraps(func)
        def wrapper(*func_args, **func_kwargs):
            print('function call ' + func.__name__ + '()')
            retval = func(*func_args,**func_kwargs)
            print('function ' + func.__name__ + '() returns ' + repr(retval))
            return retval
        return wrapper
    
    @monitor_results
    def foo():
        return 7
    
    foo()
    # prints:
    #     function call foo()
    #     function foo() returns 7