如何以编程方式更改 python 装饰器中函数的 argspec?
给定一个函数:
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
如何创建一个装饰器,使得 bare_argspec ==decorated_argspec
?
(至于为什么,调用装饰函数的框架会进行argspec检查来选择传入的内容,因此装饰器必须保留相同的argspec才能发挥良好作用。当我在#python上提出这个问题时,我得到了很长的答案关于为什么框架很糟糕的演讲,这不是我想要的;另外,我也只是对答案感兴趣)
Given a function:
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
How can I create a decorator such that bare_argspec == decorated_argspec
?
(As to why, the framework that calls the decorated function does argspec inspection to choose what to pass in, so the decorator has to retain the same argspec in order to play nice. When I posed this question on #python, I got a long speech about why the framework sucks, which is not what I'm looking for; I have to solve the problem here. Also, I'm just interested in the answer, too)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Michele Simionato 的 装饰器模块 有一个名为 Decorator 的装饰器,它保留了函数 argspecs。
Michele Simionato's decorator module has a decorator called decorator which preserves function argspecs.
有 装饰器 模块:
这使得
trace
成为具有相同功能的装饰器argspecs 作为修饰函数。例子:There's the decorator module:
That makes
trace
a decorator with the same argspecs as the decorated function. Example:functools.update_wrapper() 和/或 functools.wraps() 是否足够好?
Are
functools.update_wrapper()
and/orfunctools.wraps()
good enough?