How can I programmatically change the argspec of a function in a python decorator?

前端 未结 3 1721
醉话见心
醉话见心 2020-12-07 00:52

Given a function:

def func(f1, kw=\'default\'):
    pass
bare_argspec = inspect.getargspec(func)

@decorator
def func2(f1, kw=\'default\'):
    pass
decorate         


        
3条回答
  •  醉话见心
    2020-12-07 01:36

    There's the decorator module:

    from decorator import decorator
    @decorator
    def trace(func, *args, **kw):
        print 'calling', func, 'with', args, kw
        return func(*args, **kw)
    

    That makes trace a decorator with the same argspecs as the decorated function. Example:

    >>> @trace
    ... def f(x, y=1, z=2, *args, **kw):
    ...     pass
    
    >>> f(0, 3)
    calling f with (0, 3, 2), {}
    
    >>> from inspect import getargspec
    >>> print getargspec(f)
    ArgSpec(args=['x', 'y', 'z'], varargs='args', keywords='kw', defaults=(1, 2))
    

提交回复
热议问题