Dschoni Dschoni - 1 year ago 130
Python Question

python decorate function call

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


returning 4 without the need of having access to the implementation of
Or would in this case a global wrapper like

def mutiply(factor,function,*args,**kwargs):
return factor*function(*args,*kwargs)

be the better choice?

Answer Source

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 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download