Search code examples
pythonpython-decorators

How can I write a decorator for this simple function in Python?


for example this is my function:

def myfunc(x,y):
    print(x+y)

Now I want to write a decorator for it I want that decorator simply print "test" after x+y I mean I want next time I'm calling myfunc(x,y) I want results to be something like this

x+y   
test

The reason I'm doing this is I want to learn passing a function with arguments to a decorator , if you write a decorator for this I will learn that in this simple example. Thanks for helping


Solution

  • You can do it in this way:

    def mydecorator(f):
        def wrapper(x,y):
            print ("inside my decorator")
            f(x,y)
            print ("test")
        return wrapper
    
    @mydecorator
    def myfunc(x,y):
        print(x+y)
    
    myfunc(4,5)
    

    Output of above code execution is:

    inside my decorator
    9
    test