Instagram
youtube
Facebook
Twitter

Decorators

Introduction

  • Decorators in python are used to modify and extend the proporties of existing function.
  • In decorators functions are used as an arguments in other function and then called inside a wrapper function.
  • Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.

 

In Python, functions are first class objects. Which means we can use functions and pass them as arguments inside.

Some Proporties of Python Functions

  • A python function is an instance of object type.
  • A function can be stored inside a variable.
  • A function can be passed as an argument to a function.
  • A function could be returned as a return from another function.

 

Example - Treating a fucntion as object

# Python program to illustrate functions
# can be treated as objects
def shout(text):
    return text.upper()
 
print(shout('Hello'))
 
yell = shout
 
print(yell('Hello'))

In the above example, we have assigned the function shout to a variable. This will not call the function instead it takes the function object referenced by a shout and creates a second name pointing to it, yell.


 

Example - Calculate time for factorial function using decorators

def check_parameters (func):
    def inner(*args):
        for i in args:
            if i < 0:
                print("Do you really not know that factorial doesn't exist for the negative numbers ?")
                return
            elif not isinstance(i,int):
                print("Do'h! Only the integers have factorial.")
                return
            return func(*args)
    return inner

@check_parameters
def factorial(n):
    factorial = 1
    if n == 0:
        print("The factorial of 0 is", factorial)
    else:
        for i in range(1,n+1):
            factorial = factorial*i
        print("The factorial of", n , "is", factorial)
        
print("Case 1. Factorial of an integer")
factorial(10)

print("\nCase 2 - Factorial of a negative number")
factorial(-10)

print("\nCase 3 - Factorial of a non-integer")
factorial(10.5)