Does the decorator store more than one returned value?
I have the code:
def my_decorator(target):
def wrapper():
print('Calling function "%s"' % target.__name__)
return target() # 1
return wrapper # 2
@my_decorator
def my_target(): # 3
print('Hi. I am the target.')
my_target()
I will describe what i understand about this pattern disorderly.
#3 We are passing the function my_target as an argument to the decorator
my_decorator. No problems.
#1 Actually we are calling the function my_target.
#2 (my doubt). When we are calling the function in #1 it will print and
return to wrapper 'Hi. I am the target.' so wrapper now stores the print
from my_target function. Then, in #2 the (i do not understand this term
well ->) reference from wrapper() function is called. So after this
calling, wrapper reference will run the print('..') set in itself function
and will return the value stored before in it ('Hi. I am the target.', as
mentioned in the beginning). So, the wrapper function stores two values?
Sorry in advance for the messy thought and writing.
addendum: I do not need in #2 call the wrapper function as we call
"normal" functions with () for the same reason (that i do know why) when i
create a function and store it in a variable and when i want call it we
just type the variable and return it?
Like:
def say():
return('hello')
do = say()
>>> do
hello
No comments:
Post a Comment