DECORATORS IN PYTHON
Decorator, as the word suggests, means to decorate something. In python, we have the concept of decorating the functions/methods that are adding some extra functionality to them. In simple terms, we can define them as a function that changes the functionalities of other functions.
How To Define Decorators
We create decorators as normal functions just in this case we can also define them, pass a function as an argument. Then the name of the decorator is written with “@” as a prefix before defining any function that needs to be decorated.
A function returning another function, usually applied as a function transformation using the
Common examples for decorators are
The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:
<code>def f(...): ... f = staticmethod(f) @staticmethod def f(...): ...</code>
The same concept exists for classes but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.
There is some history in Java using @ initially as a marker in Javadoc comments and later in Java 1.5 for annotations, which are similar to Python decorators. The fact that @ was previously unused as a token in Python also means it’s clear there is no possibility of such code being parsed by an earlier version of Python, leading to possibly subtle semantic bugs. It also means that ambiguity of what is a decorator and what isn’t is removed. That said, @ is still a fairly arbitrary choice. Some have suggested using | instead.
For syntax options that use a list-like syntax (no matter where it appears) to specify the decorators a few alternatives were proposed: [|…|], *[…]*, and <…>.
Decorator To Calculate The Time Require For The Execution Of A Function
For more details checkout out the below references-
- Utkarsh Shukla Website – https://utkarshshukla.herokuapp.com/