Reputation: 4328
I'm having trouble understanding the concept of decorators, so basically if I understood correctly, decorators are used to extend the behavior of a function, without modifying the functions code . The basic example:
I have the decorator function, which take as parameter another function and then changes the functionality of the function given as argument:
def decorator(f):
def wrapper(*args):
return "Hello " + str(f(*args))
return wrapper
And here I have the function which I want to decorate :
@decorator
def text (txt):
'''function that returns the txt argument'''
return txt
So if I understand correctly , what actually happens "behind" is:
d=decorator(text)
d('some argument')
My question is , what happens in this case when we have three nested function in the decorator:
def my_function(argument):
def decorator(f):
def wrapper(*args):
return "Hello " +str(argument)+ str(f(*args))
return wrapper
return decorator
@my_function("Name ")
def text(txt):
return txt
Because the functionality is awesome, I can pass argument in the decorator, I do not understand what actually happens behind this call :
@my_function("Name ")
Thank you,
Upvotes: 3
Views: 3749
Reputation: 443
my_function
is used to create a closure here. The argument
is local to my_function
. But due to closure, when you return the decorator
, the decorator
function has a reference to it all the time. So when you apply decorator
to text
, the decorator
adds extra functionality, as to be expected. It also can embed argument
in its extra functionality since it has access to the environment in which it was defined.
Upvotes: 1
Reputation: 22979
It is just another level of indirection, basically the code is equivalent to:
decorator = my_function("Name ")
decorated = decorator(text)
text = decorated
Without arguments, you already have the decorator, so
decorated = my_function(text)
text = decorated
Upvotes: 3