Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy call signature to decorator

If I do the following

def mydecorator(f):
    def wrapper(*args, **kwargs):
        f(*args, **kwargs)
    wrapper.__doc__ = f.__doc__
    wrapper.__name__ = f.__name__
    return wrapper

@mydecorator
def myfunction(a,b,c):
    '''My docstring'''
    pass

And then type help myfunction, I get:

Help on function myfunction in module __main__:

myfunction(*args, **kwargs)
    My docstring

So the name and docstring are correctly copied over. Is there a way to also copy over the actual call signature, in this case (a, b, c)?

like image 288
astrofrog Avatar asked Jun 06 '10 03:06

astrofrog


3 Answers

Here is an example using Michele Simionato's decorator module to fix the signature:

import decorator

@decorator.decorator
def mydecorator(f,*args, **kwargs):
    return f(*args, **kwargs)

@mydecorator
def myfunction(a,b,c):
    '''My docstring'''
    pass

help(myfunction)
# Help on function myfunction in module __main__:

# myfunction(a, b, c)
#     My docstring
like image 84
unutbu Avatar answered Nov 07 '22 02:11

unutbu


Try the decorator module, available here: http://pypi.python.org/pypi/decorator/3.2.0

Relevant portion of the docs: http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem

like image 37
Arkady Avatar answered Nov 07 '22 01:11

Arkady


This functionality is supplied by the Python standard library's inspect module, specifically by inspect.getargspec.

>>> import inspect
>>> def f(a, b, c=0, *args, **kwargs): return
... 
>>> inspect.getargspec(f)
ArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(0,))
like image 1
Jordan Lewis Avatar answered Nov 07 '22 03:11

Jordan Lewis