What is the Python decorator?

Decorators are very powerful and a useful tool in Python that allows the programmers to add functionality to an existing code. This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time. It allows the user to wrap another function to extend the behaviour of the wrapped function, without permanently modifying it.

Example:

  1. def function_is_called():  
  2.     def function_is_returned():  
  3.         print(“JavaTpoint”)  
  4.     return function_is_returned  
  5. new_1 = function_is_called()  
  6. # Outputs “JavaTpoint”  
  7. new_1()  

Output:

JavaTpoint

Functions vs. Decorators

A function is a block of code that performs a specific task whereas a decorator is a function that modifies other functions.