首页 > 解决方案 > 从嵌套装饰器中获取装饰函数

问题描述

我试图从装饰器中获取对原始装饰函数的引用。如何才能做到这一点?

import inspect
from functools import wraps


def test_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # the closest I could get to getting the original function:
        # it prints the frame from which the function was called.
        current_frame = inspect.currentframe()
        outer_frames = inspect.getouterframes(current_frame)
        print(outer_frames[-1].frame)
        
        return func(*args, **kwargs)
    return wrapper


@test_decorator
@test_decorator
@test_decorator
def test_func(a, b, c):
    print("func")


test_func(1,2,3)

在这种情况下,“最初装饰的函数”是test_func,因为它是我们正在装饰的目标函数。我已经查看了该inspect模块,我能得到的最接近的方法是获取堆栈上的第一帧,但这并没有太大帮助。

也许,stdlib 中已经有解决方案了?

标签: pythondecoratorpython-decorators

解决方案


这个:

https://github.com/micheles/decorator

import inspect
from decorator import decorator


@decorator
def test_decorator(func, *args, **kwargs):
    print(inspect.getfullargspec(func))
    return func(*args, **kwargs)


@test_decorator
@test_decorator
@test_decorator
def test_func(a, b, c):
    print("func")


test_func(1,2,3)

现在从每个内部test_decorator打印:

FullArgSpec(args=['a', 'b', 'c'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})

祝福这个编写模块的人,这个人是一个传奇。


推荐阅读