Rodrigo πŸπŸš€
Rodrigo πŸπŸš€

@mathsppblog

6 Tweets Mar 18, 2023
Python 🐍 decorators are usually 2 nested functions.
If you need a decorator with arguments, then it's 3.
But how do those work?
Decorators in Python can be applied with the at operator @.
However, that is just syntactic sugar!
Using the @ before or calling the decorator after is the same thing:
So, we see that what comes after the @ is the callable that receives the function.
Hence, if your decorator accepts arguments, it must return a callable to serve as the actual decorator.
That's because, without syntactic sugar, this is what `print_args` does:
In order to implement the decorator `print_args`, you need:
- an outer function `print_args` that accepts the string prefix;
- an inner function `decorator` that will be the decorator returned; and
- an inner inner function `wrapped` that is your decorated function.
Decorators are fun πŸ˜‰
It just takes some practise.
I'll write an explanation of this that is more comprehensive in this week's newsletter issue.
If you aren't a Mathspp Insider yet, join 15k others now:
insider.mathspp.com
Remember:
Decorators are usually a function with a nested function inside.
If your decorator receives arguments, then it is going to be a function with a function inside, with a function inside.
🀯🀯

Loading suggestions...