Python Decorators

  • Python

In this tutorial, we’ll learn about python decorators and how should you use it.

Decorators in Python is a feature to add additional features to an existing function. This is just like decorating a cake with more elements that are not included in the cake.

Let’s understand python decorators using a very simple example. In this example, we’ll print the difference of two numbers like (a-b) and the difference should always be positive. But what a is smaller than b? This is what we’ll add as an extra feature to the function using another function.

def sub(a,b):
  print(a-b)

def flip(func):
  def inner(a,b):
    if a < b:
      a,b = b,a
    return func(a,b)
  return inner

obj = flip(sub)

obj(3,10)

Output :

7

First, we created a function to print the difference between two numbers, and then we created another function extra that will swap/flip the values in case the first value is smaller than the next. The extra function is a decorator that takes a function as a parameter where this feature needs to be applied.