Function Wrappers in Python

In this tutorial, we will learn how function wrappers work in Python and what it is.
They are a very powerful tool that allows programmers to modify the behaviour of the function or class.

The thoughts when translated into machine understandable codes, modification of existing function is needed. so that it has an open door to accommodate new ideas. such as adding a new argument or adding additional functionality to the function . or a little more computations which would change the dynamics of the program flow.

We know that modifying the same function, again and again, would degrade the quality of the method.

Before diving into the code, Let us Understand what Python wrappers are :

Function Wrappers

Function wrappers or Decorators are defined as one of the very powerful programming tools as it allows to modify the behaviour of the functions or classes. Therefore the possibilities are extended and the code is been reused.
In Wrappers, functions defined are taken as an argument into another function and then they are called inside the decorator function.

Syntax:-

@wrapper
def function(n):
    statements(s)

this is similar to the below code:-

def function(n):
    statement(s)

function = wrapper(function)

Example Python code to demonstrate function wrappers

# defining a WRAPPER  
def hello_dec(func):  
      
    def innerfunc():  
        print("This is before !!")  
    
        # calling actual function 
        func()  
    
        print("This is after !!")  
            
    return innerfunc
    
    
# defining a function,which is to be called inside decorator
def functionIN():  
    print("This is inside !!")  
    
    
# passing 'functionIN' as an argument inside the wrapper
functionused = hello_dec(functionIN)  
    
   
functionIN()

The decorator (hello_dec)  wraps the function around the function inner1. The functionIN() calls the pointer directly and goes to the decorator thus passing it as an argument and is executed only when called inside the function.

Output:-

This is before !! 
This is inside !!
This is after  !!

The inner1 function is executed in the same flow and the functionIN() is called only when func is called.

Leave a Reply

Your email address will not be published. Required fields are marked *