🤔 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
1️⃣0️⃣ Read more:

https://t.co/eBMh1Gv0xZ

https://t.co/2YdA2ZIQoV

https://t.co/Wb0jSjmzlc
1️⃣1️⃣ Script with all of the examples:

https://t.co/Tw1qrbN0nN

More from Machine learning

You May Also Like

I’m torn on how to approach the idea of luck. I’m the first to admit that I am one of the luckiest people on the planet. To be born into a prosperous American family in 1960 with smart parents is to start life on third base. The odds against my very existence are astronomical.


I’ve always felt that the luckiest people I know had a talent for recognizing circumstances, not of their own making, that were conducive to a favorable outcome and their ability to quickly take advantage of them.

In other words, dumb luck was just that, it required no awareness on the person’s part, whereas “smart” luck involved awareness followed by action before the circumstances changed.

So, was I “lucky” to be born when I was—nothing I had any control over—and that I came of age just as huge databases and computers were advancing to the point where I could use those tools to write “What Works on Wall Street?” Absolutely.

Was I lucky to start my stock market investments near the peak of interest rates which allowed me to spend the majority of my adult life in a falling rate environment? Yup.