2

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

2 Answers2

1

To make this work for a function with an arbitrary number of arguments you can do it this way:

def print_test(func):
  def wrapper(*args,**kwargs):
    res = func(*args,**kwargs)
    print('test')
    return res
return wrapper

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

myfunc(2,3)
Akshay Pratap Singh
  • 3,197
  • 1
  • 24
  • 33
0

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
Abhijit
  • 1,728
  • 1
  • 14
  • 25
  • You can make the decorator more generally applicable by not making any assumptions about the number of arguments of the decorated function. You should also return the return value of the decorated function. – user2390182 Dec 26 '18 at 07:27