🤔 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

10 PYTHON 🐍 libraries for machine learning.

Retweets are appreciated.
[ Thread ]


1. NumPy (Numerical Python)

- The most powerful feature of NumPy is the n-dimensional array.

- It contains basic linear algebra functions, Fourier transforms, and tools for integration with other low-level languages.

Ref:
https://t.co/XY13ILXwSN


2. SciPy (Scientific Python)

- SciPy is built on NumPy.

- It is one of the most useful libraries for a variety of high-level science and engineering modules like discrete Fourier transform, Linear Algebra, Optimization, and Sparse matrices.

Ref: https://t.co/ALTFqM2VUo


3. Matplotlib

- Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

- You can also use Latex commands to add math to your plot.

- Matplotlib makes hard things possible.

Ref: https://t.co/zodOo2WzGx


4. Pandas

- Pandas is for structured data operations and manipulations.

- It is extensively used for data munging and preparation.

- Pandas were added relatively recently to Python and have been instrumental in boosting Python’s usage.

Ref: https://t.co/IFzikVHht4

You May Also Like