python decorate function call
Solution 1
There is a very good detailed section on decorators in Marty Alchin's book Pro Python from Apress.
While the new style @decorator syntax is only available to be used at function/class definition, you can use the older syntax, which does the same thing this way:
from module import myfunc
myfunc = double_decorator(myfunc)
x = myfunc(2) # returns 4
Solution 2
You could do something like that:
def a(num):
return num * 1
def double(f):
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
return wrapped
print(double(a)(2))
It's because we can decorate functions and run functions using a decorator function explicit as in the example above. So in this one:
print(double(a)(2))
In the place of a
you can put any function and in place of the 2
, args and kwargs.
Comments
-
Dschoni about 2 years
I recently learned about decorators and wondered if it's possible to use them not in a function definition but in a function call, as some kind of general wrapper.
The reason for that is, that I want to call functions from a module through a user-defined interface that does repeatable things to a function and I don't want to implement a wrapper for every single function.
In principle I would like to have something like
def a(num): return num @double a(2)
returning 4 without the need of having access to the implementation of
a
. Or would in this case a global wrapper likedef mutiply(factor,function,*args,**kwargs): return factor*function(*args,*kwargs)
be the better choice?
-
Dschoni almost 8 yearsHow would I use that now together with the @ syntax?
-
turkus almost 8 yearsIn your case you can't. You can use @ syntax only on function declaration.
-
Dschoni almost 8 yearsThis doesn't work for me. If I change the definition of
a
to return num+1, the last line, still prints 4. -
ruohola over 5 yearsKinda bad naming of the
double
function since it doesn't actually double anything. -
InvaderZim over 2 yearsCame looking for this comment! In general terms: decorated_func_return_val = some_decorator(some_funk)(*some_args, **some_kwargs)
-
InvaderZim over 2 years@turkus: perhaps you should change it so that the wrapper actually returns double the value?
return 2 * f(*args, **kwargs)
. Or call the decorator something else, like do_nothing.