I am new to Python and decorators, so apologies if this seems to be a trivial question.
I am trying to apply decorators to multiple imported functions using a loop in Python as shown below
from random import random, randint, choice
def our_decorator(func):
def function_wrapper(*args, **kwargs):
print("Before calling " + func.__name__)
res = func(*args, **kwargs)
print(res)
print("After calling " + func.__name__)
return function_wrapper
for f in [random, randint, choice]:
f = our_decorator(f)
random()
randint(3, 8)
choice([4, 5, 6])
Ideally, I expect the output to be in this form :
Before calling random
<random_value>
After calling random
Before calling randint
<random_integer>
After calling randint
Before calling choice
<random_choice>
After calling choice
But, I am only getting the result of the choice function as the output.
<random_choice among 4,5 6>
The decorator has not been applied to any of the functions and it also looks like the random() and the randint(3,8) calls are not getting executed.
I would like to know, what is going wrong here and what can be done to decorate multiple imported functions using loops?
Thanks for the help