I’d like to decorate a function, using a pattern like this:
def deco(func):
def wrap(*a,**kw):
print "do something"
return func(*a,**kw)
return wrap
The problem is that if the function decorated has a prototype like that:
def function(a,b,c): return
When decorated, the prototype is destroyed by the varargs, for example, calling function(1,2,3,4) wouldn’t result in an exception. Is that a way to avoid that?
How can define the wrap function with the same prototype as the decorated (func) one?
There’s something conceptually wrong?
EDIT
My perverse idea was to lighten the “calling of the parent method” without modifying the signature. Something like
def __init__(self, something)
super(ClassName, self).__init__(something)
to:
@extended
def __init__(self, something):
...
I was figuring out if this was possible and if this makes sense.
EDIT
As Alex pointed out, the following code doesn’t give an exception:
function(1,2,3,4)
The decorator module helps you create a decorator that preserves the function signature.
As a result, you will get the exception you expect when calling the function, and
inspect.getargspecwill give you the correct signature.It works by dynamically building a function definition and using
exec. Unfortunately, there isn’t an easier built-in way to do this.