🤔 Python decorators

What are they? How do you use them?

🧵 Let's find out 👇
1️⃣ 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
2️⃣ 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
3️⃣ In Python, you can define a function inside other function - such functions are called inner functions
4️⃣ 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.
5️⃣ To simplify usage of decorators Python offers us syntactic sugar

A "pie-decorator" syntax using @

@decorator_name
6️⃣ 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
7️⃣ You can decorate classes too.

For example, you can dataclass decorator on your class to automatically generate its __init__ and __repr__ methods
8️⃣ You can also use a class as a decorator

Decorator class needs methods:
- __init__
- __call__ (it makes class callable)
9️⃣ For example, decorators are used for registering view functions to the Flask application
You can follow @jangiacomelli.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.