
Python decorators
What are they? How do you use them?

Let's find out

Decorator is a function or a class that wraps another function or class modifying its behavior.
So how does that work?
The first thing to know is that everything in Python is an object - functions too

That means they can be passed to another function as an argument or returned from a function
Functions that take other functions as an argument are called higher-order functions

In Python, you can define a function inside other function - such functions are called inner functions

To create a decorator you just need to apply all of that together
log_enter_leave is a decorator.
my_function is the function.
To alter my_function's behavior we reassign it applying log_enter_leave decorator.

To simplify usage of decorators Python offers us syntactic sugar
A "pie-decorator" syntax using @
@decorator_name

The only problem here is that my_function now identify as the wrapper function
To solve that we just need to use wraps from functools

You can decorate classes too.
For example, you can dataclass decorator on your class to automatically generate its __init__ and __repr__ methods

You can also use a class as a decorator
Decorator class needs methods:
- __init__
- __call__ (it makes class callable)

For example, decorators are used for registering view functions to the Flask application
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.