Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preserve argspec when decorating? [duplicate]

Tags:

python

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

argspec is a great way to get arguments of a function, but it doesn't work when the function has been decorated:

def dec(func):
    @wraps(func)
    def wrapper(*a, **k)
        return func()
    return wrapper


@dec
def f(arg1, arg2, arg3=SOME_VALUE):
    return

import inspect
print inspect.argspec(f)

-----------

ArgSpec(args=[], varargs='a', keywords='k', defaults=None)

Argspec should return arg1, arg2, arg3. I think I need to define wrapper differently as to not use *a and **k, but I don't know how.

like image 886
priestc Avatar asked Sep 24 '12 03:09

priestc


1 Answers

The decorator module preserves them fine:

from decorator import decorator
@decorator
def dec(func, *a, **k):
    return func()

@dec
def f(arg1, arg2, arg3=1):
    return

import inspect
print inspect.getargspec(f)
ArgSpec(args=['arg1', 'arg2', 'arg3'], varargs=None, keywords=None, defaults=(1,))

You probably can get the same effect by manually copying some __foo__ attributes from the function to the wrapper function, but anyway the decorator module demonstrates it's possible and maybe gives you a starting point.

like image 57
Mu Mind Avatar answered Nov 14 '22 14:11

Mu Mind