Decorators are one of the most powerful feature of Python! 🔥
However, understanding them can be a bit overwhelming!
Today, I'll clearly explain how decorators work!
Let's go! 🚀
Before we jump onto decorator, we must understand that functions in python are "first-class" objects!
It means that a function can be:
- passed around as an argument
- used in expressions
- returned as values of other functions
Just like integers or string!
Check this out👇
To get the essence of Decorators, let's imagine it's your friend's birthday, you're giving them a gift.
But before you do, you wrap it in a fancy gift paper to enhance its look, right?
Decorators do the same thing but with functions. ✨
Let's see how ... 👇
Decorators are a bit like wrapping paper.
They're functions that take another function, add some functionality, and return the new "decorated" function.
Check this out👇
The syntax we saw above is a bit clumsy.
However Python has a subtle way to do it! 💫
We can use the `@` symbol along with the decorator name right before the function definition.
It does exactly the same thing as before but looks cleaner!✨
Check this out👇
Now if you are wondering, what happens when my function takes an argument!
Here'a an illustration of how decoration works when the function being greeted takes an argument!
Check this out👇
Decorators are powerful and flexible.
They can be used to:
- log function calls
- check function arguments
- run code before and after functions,
- and much more ...
They allow us to add functionality in a clean, consistent way.
Here's an interesting & generic use-case 👇
That's a wrap!
If you interested in:
- Python 🐍
- Maths for ML 🧮
- ML/MLOps 🛠
- CV/NLP 🗣
- LLMs 🧠
- Ai Engineering ⚙️
Find me → @akshay_pachaar ✔️
I also write a technical newsletter on AI Engineering!
Join 4.5K+ readers: mlspring.beehiiv.com/subscribe
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.