Saturday 13 November 2021

Python: Working with decorators

Decorators is one of the powerful concepts in Python, it allows you to modify the behaviour of a function or class without touching the actual function definition.

 

For example, there is a function ‘add’ that takes two integers as input and return the sum of these two numbers. Now I want to log the inputs before for every addition operation that I am going to perform. Let’s see how can I achieve this without touching actual add function definition.

 

Step 1: Define a function ‘add’ that takes two arguments and return the sum of two numbers.

 

def add(a, b):
    return a + b

Step 2: Define a function that takes a function as argument and write some wrapper logic and call the actual add function.

 

def logAndAdd (func):
    def log(a, b):
        print('inputs: ', a, b)
        return func(a, b)
    return log

 

Step 3: Now you can redefine add method like below.

add = logAndAdd(add)

 

Find the below working application.

 

decorator_demo_1.py

def add(a, b):
    return a + b

def logAndAdd(func):
    def log(a, b):
        print('inputs: ', a, b)
        return func(a, b)
    return log


add = logAndAdd(add)
print('sum of 10 and 20 is ', add(10, 20))

 

Output

inputs:  10 20
sum of 10 and 20 is  30

 

Python provides an efficient way to apply decorators to a function. We simply use the @ symbol before the function we'd like to decorate.

 

Example

 

@logAndAdd
def add(a, b):
    return a + b


decorator_demo_2.py

def logAndAdd(func):
    def log(a, b):
        print('inputs: ', a, b)
        return func(a, b)
    return log

@logAndAdd
def add(a, b):
    return a + b

print('sum of 10 and 20 is ', add(10, 20))


Output

inputs:  10 20
sum of 10 and 20 is  30


Can I apply multiple decorators to a function?

Yes, you can do.

 

Example

@printHeader
@timestamp
def add(a, b):
    return a + b


decorator_demo_3.py

import datetime

def timestamp(func):
    def log(a, b):
        print('time ', datetime.datetime.now())
        return func(a, b)
    return log

def printHeader(func):
    def log(a, b):
        print('---------------------------')
        print('Calculationg sum of two numbers')
        print('a = ', a)
        print('b = ', b)
        print('---------------------------')
        return func(a, b)
    return log

@printHeader
@timestamp
def add(a, b):
    return a + b

print('sum of 10 and 20 is ', add(10, 20))


Output

---------------------------
Calculationg sum of two numbers
a =  10
b =  20
---------------------------
time  2021-08-26 17:50:24.056033
sum of 10 and 20 is  30


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment