Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 720
trident Avatar asked Sep 05 '26 14:09

trident


1 Answers

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
like image 167
Tamas Hegedus Avatar answered Sep 07 '26 08:09

Tamas Hegedus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!