python装饰器打印返回值

tri*_*ent 3 return decorator python-3.x

这个问题涉及Python 3。有没有办法让装饰器打印任何函数的返回值?这个问题装饰器打印函数调用详细信息 - 参数名称和有效值将打印您传递给函数的所有值。有没有办法让装饰器打印函数返回的值,无论它返回单个值还是多个值?

所以如果你要运行这个:

multiply(subtract(add(1,2),add(3,4)),9)
Run Code Online (Sandbox Code Playgroud)

所有用 @superecho 修饰的函数都会记录:

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
Run Code Online (Sandbox Code Playgroud)

Tam*_*dus 7

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
Run Code Online (Sandbox Code Playgroud)