Skip to content Skip to sidebar Skip to footer

How Can I Programmatically Change The Argspec Of A Function In A Python Decorator?

Given a function: def func(f1, kw='default'): pass bare_argspec = inspect.getargspec(func) @decorator def func2(f1, kw='default'): pass decorated_argspec = inspect.getargs

Solution 1:

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

import inspect
import decorator

deffunc(f1, kw='default'):
    pass
bare_argspec = inspect.getargspec(func)
print(bare_argspec)
# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('default',))@decorator.decoratordefmydecorator(func,*args,**kw):
    result=func(*args,**kw)
    return result

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

Solution 2:

There's the decorator module:

from decorator import decorator
@decoratordeftrace(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...deff(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))

Solution 3:

Are functools.update_wrapper() and/or functools.wraps() good enough?

Post a Comment for "How Can I Programmatically Change The Argspec Of A Function In A Python Decorator?"