python中的Interceptor如何应用

How can Interceptor in python be applied

我需要知道函数何时被调用并在调用函数后做一些事情。看来 Interceptor 可以做到。

如何在 python 中使用拦截器?

这可以使用装饰器来完成:

from functools import wraps


def iterceptor(func):
    print('this is executed at function definition time (def my_func)')

    @wraps(func)
    def wrapper(*args, **kwargs):
        print('this is executed before function call')
        result = func(*args, **kwargs)
        print('this is executed after function call')
        return result

    return wrapper


@iterceptor
def my_func(n):
    print('this is my_func')
    print('n =', n)


my_func(4)

输出:

this is executed at function definition time (def my_func)
this is executed before function call
this is my_func
n = 4
this is executed after function call

@iterceptor 将 my_func 替换为 iterceptor 函数的执行结果,即 wrapper 函数。 wrapper 在一些代码中包装给定的函数,通常保留 wrappee 的参数和执行结果,但添加一些额外的行为。

@wraps(func)是为了将函数func的signature/docstring数据复制到新创建的wrapper函数中。

更多信息: