What Are Decorators In Python?

What Are Decorators In Python?

Published on October 03 2023

In this tutorial, we will learn what decorators are in Python and understand them in detail with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • Decorators are functions that add functionality to an existing function in Python without changing the structure of the function itself.
  • It receives a function as input and returns a function as output.
  • represented by @decorator_name

Steps

  • To apply a decorator we first define the decorator function.
  • Then we write the function it is applied to
  • and simply add the decorator function above the function it has to be applied to.

Sample Decorator

@validate_divide_inputs_function
def perform_divide(x, y):

Applications

  • These are useful when we want to dynamically increase the functionality of an existing function without changing it.
  • validating input data, enforcing access control and authentication, caching, etc.

Example

def validate_divide_inputs_function(func):
    def inner_validation_function(x, y):
        if y == 0:
            print('Cannot divide by 0')
            return
        else: # else can be avoided
            result_op = func(x,y)
            return result_op
    return inner_validation_function

@validate_divide_inputs_function
def perform_divide(x, y):
    result = x / y
    return result

output_result = perform_divide(102,0)
print(output_result)

To know about it, please refer to the official documentation website - official website.

Example Video