6 Secret Examples To Understand Python Wrappers

Hello Geeks, I hope all are doing great. So in this article, we will learn about python wrappers. First, we will see what wrappers are and then some of the examples. So, Let’s get started.

What are Wrappers in Python?

So, wrappers are the functionality available in Python to wrap a function with another function to extend its behavior. Now, the reason to use wrappers in our code lies in the fact that we can modify a wrapped function without actually changing it. They are also known as decorators.

We can do this by passing a function (let say function1) inside another function (let say function2) as the argument and then making a function call inside a wrapper function within function2. Let’s see some examples to understand it clearly.

Example 1:-

# defining decorator function named as function1
def function2(function1):
  # defining wrapper function
  def wrapper_function():
    return function1()
  return wrapper_function

# Function we want to wrap
def function1():
  print("This is wrapped function.")

# Holds the returned function in a variable
var = function2(function1)
# executing var function
var()
Output:

This is wrapped function.

Example 2:-

We can also achieve wrappers using another method. Let’s see this.

# defining decorator function
def decorator_function(wrapped_function):
  def wrapper_function():
    return wrapped_function()
  return wrapper_function

@decorator_function
def wrapped_function():
  print("This is wrapped function")

wrapped_function()
Output:

This is wrapped function

So, in the above example, we first created a function that wraps a function named as wrapper function inside the decorator function. After that, we created a function that needed to be covered. Above the wrapped_function, we defined a statement @decorator_function, which says that we are passing the function as an argument of the decorator function. The returned value is stored in the wrapped_function variable, which is hidden, and then we need to call it for execution.

Passing Arguments in Wrapper Function

We can also pass the arguments in the wrapper function. Let’s see n example and understand how we can do it.

Example 3:

# defining decorator function
def decorator_function(wrapped_function):
  def wrapper_function(a,b,*args,**kwargs):
    return wrapped_function(a,b,*args,**kwargs)
  return wrapper_function

@decorator_function
def wrapped_function(a,b,*args,**kwargs):
  print("Inside wrapped function")
  print('a=',a,'b=',b)
  print('args:',args)
  print('kwargs:',kwargs)

a = 10
b = 20
wrapped_function(a,b,30,40,c=50,d =60)
Output:

Inside wrapped function
a= 10 b= 20
args: (30, 40)
kwargs: {'c': 50, 'd': 60}

Wrapper Classes in Python

Python wrapper classes are almost as similar as the python wrapper function. They are used to manage classes when their instance is created or maybe sometime later by wrapping the logic. They are syntactically similar to the python wrapper function. Let’s see some examples of it.

Example 4:

def decorator_function(Wrapped):

  class Wrapper:

    def __init__(self,x):
      self.wrap = Wrapped(x)
    def print_name(self):
      return self.wrap.name
  return Wrapper

@decorator_function
class Wrapped:
  def __init__(self,x):
    self.name = x

obj = Wrapped('PythonPool')
print(obj.print_name())
Output:

PythonPool

Let’s see the explanation of the above example. So first, we created a class that we wanted to wrap named ‘Wrapped.’ Then, we created a decorator function and passed the wrapped class as an argument. After that, we created a wrapper class inside the decorator function. Then, we defined the init method inside it, which initializes its object when called. After that, we defined another function inside it that works accordingly, and then we return that object to where it is called. Once we get the object of the wrapper class, we can extend the behavior of the wrapped class with attributes of the wrapper class.

Multiple Wrappers in Python

So, till now, we have seen how we can use wrapper functions and wrapper classes to extend the behavior of our code. Now the question arose that can we use multiple decorators in Python. So the precise answer to this is yes, we can do it. Let’s see that.

So the method of using multiple wrappers is known as Decorator Chaining. The procedure of defining multiple is pretty similar to the single wrapper. We need to define two decorator functions and then separately mention them using the “@” operator. Let’s see an example to understand it more clearly.

Example 5:

def decorator1(func):
  def wrapper1(a):
    a = a+"I am in wrapper1"
    return func(a)
  return wrapper1


def decorator2(func):
  """Comment"""
  def wrapper2(a):
    a = a+" and now in wrapper 2"
    return func(a)
  return wrapper2

@decorator1
@decorator2
def func(a):
  print(a)


a = ""
func(a)
  
Output:

I am in wrapper1 and now in wrapper 2

So, in the above example, we have first created our first decorator and then the second decorator. While calling the decorator, we must remember that the above decorator is called first rather than close to the function. So in the above case, you can see that decorator1 is called first and then decorator second.

Getting Name of Wrapped/Decorated Function

We can also get the name of the decorated function. To do that, we will use the following block of code.

Example 6:

# defining decorator function
def decorator_function(wrapped_function):
  def wrapper_function():
    return wrapped_function()
  return wrapper_function

@decorator_function
def wrapped_function():
  print("This is wrapped function")


wrapped_function()
wrapped_function.__name__
Output:

This is wrapped function
wrapper_function

Wrapper vs Library

Many people get confused in libraries and wrappers. However, they are two different things and are used at different places. Let’s understand them.

LibraryWrappers
library is typically an actual concrete implementation of some functionality. wrapper is mostly just a layer of abstraction around existing functionality. It is only intended to offer a better, cleaner interface (or at least one feels more native to the language or technology it targets) to existing ones.
They are used to extend the scope of our project.They are used to extend the scope of any particular function or class.

Example 7: API Wrapper

However, while working with APIs, we often hardcode the API calls or requests. But, it is pretty exciting and easy if we use python wrappers for doing the same. The very first question to our mind is how we can do it. Let’s see the code for doing it.

import requests
class APICall():  
    def __init__(self, api_key):
        session = requests.Session()
        self.session = session
        self.key=api_key
    def other_functions():
        """ do something"""

obj = APICall(<API KEY>)
obj.other_functions()

In the above case, we have defined a class for handling events related to API calls.

FAQs on Python Wrapper

Q1) Can we use multiple wrappers in Python?

Yes, we can use multiple wrappers in Python. The method is known as chain multiple decorators or Decorator Chaining.

Q2) Can we perform the unit test for the python wrapper?

Yes, the “unittest” module provides us the functionality of testing our code within a wrapper. Besides that, we can also use the doctest module for testing wrappers in our code.

Click here to learn about the doctest module.

Q3) How can we wrap C++ code in our python module?

We can wrap C++ code by using Boost. Python Module. It provides us the functionality of interaction between Python and C++ code.

Q4) How can use Python for Java Platforms?

We can do that by using Jython. It provides us the interface of running our python code on java applications.

Conclusion

So, today in this article, we learned how to use the wrapper function in our code and extend the behavior of any function. We have also seen some of the examples of it.

I hope this article has helped you. Thank You.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments