Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python decorators with arguments

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,

like image 226
dejanualex Avatar asked Feb 24 '26 20:02

dejanualex


1 Answers

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
like image 90
BlackBear Avatar answered Feb 27 '26 09:02

BlackBear