+ 2

when do you use decorator in python?

Some python projects I see use decorators in their code. But until now, I never got the concept, then I want to know, how, when and why to use decorator?

28th Sep 2022, 9:36 AM
Mikaia Randrianjafy
Mikaia Randrianjafy - avatar
2 Respostas
+ 3
"By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it." [Real Python] A good way to understand decorators is writing one. Decorators are also briefly explained in the Python Core course. Python decorators: https://www.sololearn.com/learn/Python/2463/?ref=app https://www.sololearn.com/Course/Python/?ref=app https://pythonbasics.org/decorators/ https://realpython.com/primer-on-python-decorators/ https://datagy.io/python-decorators/
28th Sep 2022, 11:15 AM
Lisa
Lisa - avatar
+ 1
There are some particular cases when you want to give superpowers to the functions you are writing. Some notable examples from the standard library: @property @staticmethod @functools.lru_cache @contextlib.contextmanager You can write your own decorator too, for example to measure the execution time of your functions, you can find many tutorials online that cover this case. For me, the caching decorator has proven to be the most useful. https://code.sololearn.com/cWpFUu2kmHLZ/?ref=app https://code.sololearn.com/cDT8ZI7T06of/?ref=app
30th Sep 2022, 5:43 AM
Tibor Santa
Tibor Santa - avatar