Decorators

Decorator factories and stacking decorators

What if the decorator itself needs an argument, like @repeat(3)? You wrap one more level: a function that returns a decorator. The lesson also shows what happens when several @ lines stack on the same function.


Sometimes the decorator itself needs an argument, like @repeat(3). The previous decorators just took a function. To accept an argument, you need one more layer.

A decorator factory is a function that returns a decorator. Three nested defs:

Python

Now @repeat(3) works because repeat(3) returns a decorator:

Python
Output

What will be the output?

Python

You can stack multiple decorators by listing them above the function. They apply bottom up: the one nearest the def runs first.

Add one and double, applied in different orders:

Python
Output

Reading bottom up: value returns 5, add_one makes it 6, then double makes it 12. Reverse the order and you get (5 * 2) + 1 = 11.


What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

Decorator factories are useful when behaviour depends on a value (count, role name, retry limit). Stacking lets you compose small decorators into larger pipelines.


What will be the output?

Python