Python Programming Decorators

What is python decorators?

  • Python decorators allow to dynamically change the behavior or extend the functionality of existing functions or classes without changing the definition.
  • Powerful tool for writing clean, dynamic code in python.
  • @ symbol is used to apply the decorators.
    @my_decorator
    def show_message(msg):
        # my_decorator stuff goes here
        return msg;
    
  • Python decorators are not an implementation of the decorator pattern.
  • Python decorators add functionality to functions at definition time, not at run time.

Python decorator wrapping function

Decorators wrap a function and modifying its behavior. before and after adding functionalities for actual python function.
def my_decorator(func):                                                         
                                                                                
    def decorator():                                                            
        print("Before func() is called.")                                       
        func()                                                                  
        print("After func() is called.")                                        
                                                                                
    return decorator;                                                           
                                                                                
                                                                                
def show_message():                                                             
    print("Welcome to python decorators!");                                     
                                                                                
show_message = my_decorator(show_message);                                      
show_message();   
Output:
$ python test_decorators.py
Before func() is called.
Welcome to python decorators!
After func() is called.

Creating function decorator in python

Create decorators.py file with below code.
def my_decorator(func):                                                         
                                                                                
    def decorator():                                                            
        print("Before func() is called.")                                       
        func()                                                                  
        print("After func() is called.")                                        
                                                                                
    return decorator;                                                           
                                                                                
                                                                                
if __name__ == "__main__":                                                      
    my_decorator()                                                              

Adding decorator to function in python

Create test_decorators.py with below code.
from decorators import my_decorator;                                            
                                                                                
@my_decorator                                                                   
def show_message():                                                             
    print("Welcome to python decorators!");                                     
                                                                                
show_message();    
Output:
$ python test_decorators.py
Before func() is called.
Welcome to python decorators!
After func() is called.

Creating method decorator with parameters

from time import sleep                                                          
                                                                                
def my_decorator(function):                                                     
                                                                                
    """                                                                         
    Adds string contenation and sleeping time in decorator.                     
    """                                                                         
                                                                                
    def decorator(*args, **kwargs):                                             
        sleep(2)                                                                
        return "Welcome to " + function(*args, **kwargs)                        
    return decorator;                                                           
                                                                                
                                                                                
@my_decorator                                                                   
def show_message(msg):                                                          
    return msg;                                                                 
                                                                                
print(show_message("python decorator!"));   
Output:
$ python test_decorators1.py
Welcome to python decorator!

Creating decorator with parameters

                                                                                                                                
def add_decorator(add_val):                                                     
                                                                                
    """                                                                         
    Adds decorator param with function return value.                     
    """                                                                         
    def addition_generator(old_function):                                       
        def new_function(*args, **kwds):                                        
            return add_val + old_function(*args, **kwds);                       
        return new_function;                                                    
    return addition_generator; #it returns the new generator                    
                                                                                
@add_decorator(5)                                                               
def addition(val):                                                              
    return val;                                                                 
                                                                                
print("sum: " + str(addition(6)));  
Output:
$ python test_decorators1.py
sum: 11

Nesting decorators in python

decorator syntax can be nested.
from time import sleep                                                          
                                                                                
def my_decorator(function):                                                     
                                                                                
    """                                                                         
    Adds string contenation and sleeping time in decorator.                     
    """                                                                         
                                                                                
    def decorator(*args, **kwargs):                                             
        sleep(2)                                                                
        return "sum: " + str(function(*args, **kwargs));                        
    return decorator;                                                           
                                                                                
def add_decorator(add_val):                                                     
                                                                                
    """                                                                         
    Adds string contenation and sleeping time in decorator.                     
    """                                                                         
    def addition_generator(old_function):                                       
        def new_function(*args, **kwds):                                        
            return add_val + old_function(*args, **kwds);                       
        return new_function;                                                    
    return addition_generator; #it returns the new generator                    
                                                                                
@my_decorator                                                                   
@add_decorator(5)                                                               
def addition(val):                                                              
    return val;                                                                 
                                                                                
print(addition(6));  
Output;
$ python test_decorators1.py
sum: 11

Python class decorators

  • Just like functions, classes can also have decorators in python.
  • class decorators are used to add the required functionality that maybe external to the class implementation.
def singleton(class_name):                                                      
    object_list = {};                                                           
                                                                                
    def get_object():                                                           
        if class_name not in object_list:                                       
            object_list[class_name] = class_name();                             
        return object_list[class_name];                                         
                                                                                
    return get_object;                                                          
                                                                                
@singleton                                                                      
class Math(object):                                                             
    pass                                                                        
                                                                                
a = Math();                                                                     
print "a: ", id(a);                                                             
                                                                                
b = Math();                                                                     
print "b: ", id(b)                                                              
                                                                                
print "a and b is: ",  id(a) == id(b) 
Output:
$ python test_decorators2.py
a:  140342052585296
b:  140342052585296
a and b is:  True

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^