python - 从嵌套装饰器中获取装饰函数
问题描述
我试图从装饰器中获取对原始装饰函数的引用。如何才能做到这一点?
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 中已经有解决方案了?
解决方案
这个:
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={})
祝福这个编写模块的人,这个人是一个传奇。
推荐阅读
- r - 从 Rcpp 中的 beta 分布生成样本的更好方法
- mysql - 如何在 RDS MySQL 中限制非 SSL 连接
- c# - How to change FontStyle back in RichTextBox?
- wpf - 如何在 XAML 中将直线剪裁成椭圆
- r - Rbind 使用 R 将文件名/模式包含在源文件的列中的文件
- javascript - 我如何获得 Axios 发布请求正在进行中
- html - 我是这个 html 和 css 编码的新手,它无法识别 mp3,我该如何编码才能识别它?
- java - PKIX 路径构建在开发环境中失败,但在 localhost 中失败
- python - 在 Python 中发送带有有效负载的 GET 请求
- adobe - Adobe LiveCycle 中带有可流动内容的分页符