从嵌套装饰器中获取装饰函数
Get decorated function from within nested decorator
我正在尝试从装饰器中获取对最初装饰函数的引用。如何做到这一点?
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)
在此上下文中的 'originally decorated function' 将是 test_func
,因为它是我们正在装饰的目标函数。我查看了 inspect
模块,我能得到的最接近的是在堆栈上获取第一帧,但它没有太大帮助。
也许,stdlib 中已经有解决方案了?
这个:
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={})
祝福这个编写模块的人,他是一个传奇。
我正在尝试从装饰器中获取对最初装饰函数的引用。如何做到这一点?
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)
在此上下文中的 'originally decorated function' 将是 test_func
,因为它是我们正在装饰的目标函数。我查看了 inspect
模块,我能得到的最接近的是在堆栈上获取第一帧,但它没有太大帮助。
也许,stdlib 中已经有解决方案了?
这个:
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={})
祝福这个编写模块的人,他是一个传奇。