Search code examples
pythondecoratorpython-decorators

Can we apply python decorator at function invoke?


Say for example I have a function

def A(): pass

I call this function from two different places

def B():
    #some code
    A()
    #some code

def C():
    #some code
    A()
    #some code

Decorators as we know, in layman language is something like a hook which lets you perform a set of operation before and after the function call. We apply decorators on function definition using @.

My requirement here is like I don't want the decorator to be applied every time the function is called. Like in the above example if I apply decorator on function A. It would be applied in both invokes. Can we use @ at the invoke of the function A?

Something like,

def A(): pass

def B():
    #some code
    A()
    #some code

def C():
    #some code
    @decorator
    A()
    #some code

This way I don't have to worry about merging my code after every release of particular opensource project.


Solution

  • A decorator is just syntactic sugar, where the outcome of the @expression is called and the return value is used to replace the decorated object.

    If you only need to have a decorated function in one location you can do decorator(A)() to have it return a decorated version just to be used in C and call that decorated object on the spot.

    Better yet, store that decorated version for C to use so you don't keep decorating it each time:

    A_decorated = decorator(A)
    
    def C():
        # some code
        A_decorated()
        # some code