Search code examples
pythonwrapperdecorator

python decorate function call


Is it possible to wrap a function call using python decorators?

I don't want to implement a wrapper for every function of a module individually.

I would like to have something like

def a(num):
    return num

@double_the_value
a(2)

returning 4 without the need of having access to the implementation of a.

Would a global wrapper like

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

be the better choice in this case?


Solution

  • While the @decorator syntax is only available to be used in conjunction with the definition of a function or class, the syntax before decorators became a language feature can do what you request:

    from module import myfunc
    
    myfunc = double_decorator(myfunc)
    
    x = myfunc(2) # returns 4
    

    Further Reading: There is a very good detailed section on decorators in Marty Alchin's book Pro Python from Apress.