Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator execution order

People also ask

What order are decorators executed in Python?

During the definition, decorators are evaluated from bottom to top meanwhile during the execution (which is the most important part in general) they are evaluated from top to bottom.

Does decorator order matter?

The Flask documentation specifies that the order matters if the function is a view and has a route decorator. From the docs: When applying further decorators, always remember that the route() decorator is the outermost.

Can decorators be chained?

Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python.

What are decorator functions?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.


Decorators wrap the function they are decorating. So make_bold decorated the result of the make_italic decorator, which decorated the hello function.

The @decorator syntax is really just syntactic sugar; the following:

@decorator
def decorated_function():
    # ...

is really executed as:

def decorated_function():
    # ...
decorated_function = decorator(decorated_function)

replacing the original decorated_function object with whatever decorator() returned.

Stacking decorators repeats that process outward.

So your sample:

@make_bold
@make_italic
def hello():
  return "hello world"

can be expanded to:

def hello():
  return "hello world"
hello = make_bold(make_italic(hello))

When you call hello() now, you are calling the object returned by make_bold(), really. make_bold() returned a lambda that calls the function make_bold wrapped, which is the return value of make_italic(), which is also a lambda that calls the original hello(). Expanding all these calls you get:

hello() = lambda : "<b>" + fn() + "</b>" #  where fn() ->
    lambda : "<i>" + fn() + "</i>" # where fn() -> 
        return "hello world"

so the output becomes:

"<b>" + ("<i>" + ("hello world") + "</i>") + "</b>"