DEV Community

Dmusketeer
Dmusketeer

Posted on

Decorators in Python

let’s understand what is decorators in python and how it work …

Image description

  • Decorators are evolved from the concept of closures.
  • A decorator function is a higher order function that takes a function as an argument and returns the inner function.
  • A decorator is capable of adding extra functionality to an existing function, without altering it.
  • The decorator function is prefixed with @ symbol and written above the function definition.

Consider the below three examples:

I. First one shows the creation of closure function wish using the higher order function outer.
II. The second one shows the creation of decorator function outer, which is used to decorate function sayHello. This is achieved with a small change to Example1.
III. Third one displays decorating the sayHello function with decorator function, outer, using @ symbol.

Example 1:

Image description

  • wish is the closure function obtained by calling an outer function with the argument sayHello.
  • When wish function is called, inner function gets executed.

Output
Accessing : sayHello
Hello!

Example 2:

Image description

Output
Accessing : sayHello

  • The function returned by outer is assigned to sayHello i.e the function name passed as argument to outer.
  • This makes outer a decorator to sayHello. In Python, decorating a function can also be achieved by writing decorator function name, prefixed with @ symbol, just above the function to be decorated.
  • Hence,sayHello = outer(sayHello) expression is same as @outer.

Example 3:

Image description

Output
Accessing : sayHello

Conclusion
The intent of this article is to give you enough information about python decorators through examples.

Top comments (0)