本文介绍了如何在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 ==装饰型argspec

How can I create a decorator such that bare_argspec == decorated_argspec?

(至于为什么,调用装饰函数的框架会进行argspec检查以选择要传递的内容,因此装饰器必须保留相同的argspec以便玩得开心。当我在#python上提出这个问题时,我做了很长的演讲,说明为什么框架很烂,这不是我想要的;我必须在这里解决问题。我也只是对答案感兴趣)

(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)

推荐答案

Michele Simionato的具有一个称为装饰器的装饰器,用于保留argspecs函数。

Michele Simionato's decorator module has a decorator called decorator which preserves function argspecs.

import inspect
import decorator

def func(f1, kw='default'):
    pass
bare_argspec = inspect.getargspec(func)
print(bare_argspec)
# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('default',))

@decorator.decorator
def mydecorator(func,*args,**kw):
    result=func(*args,**kw)
    return result

@mydecorator
def func2(f1, kw='default'):
    pass
decorated_argspec = inspect.getargspec(func2)
print(decorated_argspec)
# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('default',))

assert(bare_argspec==decorated_argspec)

这篇关于如何在python装饰器中以编程方式更改函数的argspec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 13:17