d
WE ARE EXPERTS IN TECHNOLOGY

Let’s Work Together

n

StatusNeo

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.

Syntax

Demo Syntax

A function returning another function, usually applied as a function transformation using the @wrapper syntax.
Common examples for decorators are classmethod() and staticmethod().

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.

Why @?

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

Sample Code to demonstrate

For more details checkout out the below references-

  1. https://www.python.org/dev/peps/pep-0318/

Still Curious? Visit my website to know more!

For more interesting Blogs Visit- Utkarsh Shukla Author

Disrupting the Tech World: Product Owner at NerdyBio, Python Powerhouse, AWS Ace & Prolific Tech Blogger 💻💥

Add Comment