tags:

views:

44

answers:

1

I need to determine the argspec (inspect.getargspec) of a function within a decorator:

def decor(func):
    @wraps(func)
    def _decor(*args, **kwargs):
        return func(*args, **kwargs)
    return _decor

@decor
def my_func(key=1, value=False):
    pass

I need to be able to inspect the wrapped "my_func" and return the key/value arguments and their defaults. It seems that inspect.getargspec doesn't get the proper function.

(FWIW I need this for some runtime inspection/validation and later documentation generation)

+3  A: 

If you use Michele Simionato's decorator module to decorate your function, its decorator.decorator will preserve the original function's signature.

import inspect
import decorator

@decorator.decorator
def decor(my_func,*args,**kw):
    result=my_func(*args,**kw)
    return result

@decor
def my_func(key=1, value=False):
    pass
decorated_argspec = inspect.getargspec(my_func)
print(decorated_argspec)
# ArgSpec(args=['key', 'value'], varargs=None, keywords=None, defaults=(1, False))
unutbu