Menu Close

Monkey Patching in Python

monkey patching in Python

Hello Programmers, In this Python guide, I am going to teach you about an exciting topic of Python which is called monkey patching. monkey patching in Python is one of the best ways to modify functions, classes, and modules behaviors dynamically ( at run time ).

Basically, monkey patching comes under the advanced topics in Python and it is asked by most the interviewer especially when you are going to attend an interview for a Python developer or Django Developer.

Throughout this article, we will explore, monkey patching in Python with examples so that you can get more clarity. After this guide, you wouldn’t have any confusion regarding Monkey Patching in Python.

What is Monkey Patching in Python?

Monkey patching in Python is a process of altering the functionality of existing classes, methods, functions, and modules at run time. Being an interpreted language, Python allows performing modification on run time. this is why it is called a great feature of Python. Monkey patching has been asked in Many interviews even I have experienced it also.

OR

Monkey patching is just a piece of Python code that is used to change the behavior of existing code dynamically.

Why do we need monkey patching in Python?

As we know very well, Python is a dynamic language, which means it gives us full access to change the functionality or you can say the behavior of existing code at run time.

Let’s understand the Python monkey patching concept with the help of real-life examples so that you can get more awareness of this concept.

Suppose, When you are working on any realistic Python project, It might be, you face some issues where a module, class, or function is not working fine, in that situation you can modify the behavior of that module, class, or function by using this amazing concept called monkey patching.

Let’s understand Python monkey patching with a proper example.

Monkey Patching in Python with Example

In this examples section, we will try to change the behavior of the class method, function, and module, so that you can understand properly.

First will try to change the behavior of the Python function.

Example: Changing the behavior of the Python function

In the below piece of code, I have created two functions named addition and multiplication, addition function takes two arguments x, and y, and performs arithmetic addition of those two arguments, and the same multiplication function also takes two parameters and performs arithmetic multiplication of those two params.

let’s call these both functions along with parameters.

def addition(x, y):
    print(f"Addition of {x} and {y} is:- ", x + y)

def multiplication(x, y):
    print(f"Multiplication of {x} and {y} is:- ", x * y)

addition(12, 34)
multiplication(12, 34)

Output

Addition of 12 and 34 is:-  46
Multiplication of 12 and 34 is:-  408

If you getting the above output it means your code running successfully but so far I haven’t applied the concept of Monkey Patching yet. But now, I want to change the whole behavior of the addition function with the behavior multiplication function which means from now, when we call the addition function it should calculate the multiplication of two numbers instead of addition. This will be done using the monkey patching concept. Let’s see.

In the below code at line no 10, You can see, How I am changing the behavior of the addition function, before line number 10 it will calculate addition obviously.
Now, when we will call the addition function along with parameters, it will calculate multiplication instead of addition.

def addition(x, y):
    print(f"Addition of {x} and {y} is:- ", x + y)

def multiplication(x, y):
    print(f"Multiplication of {x} and {y} is:- ", x * y)


addition(12, 34)
# change the behaviour of addition
addition = multiplication
addition(100, 12)

Output

Addition of 12 and 34 is:-  46
Multiplication of 100 and 12 is:-  1200

So, this is how we can alter the behavior of any Python function at run time.

Now let’s move to another section where we will try to alter the functionality of the Python module using the monkey patching concept.

Note:- A module in Python is file contains some definitions and statements.A Python module can define classes, functions and variables and it can also contains runnable code.A collections of Python modules is called package and every packages in Python must have __init__.py file.

Apply monkey patching on the Module in Python

We have a Python file employee.py having some Python code. Inside this module, We have defined a class Employee which has an instance method full_name that takes the first_name and last_name of the Employee class object as a parameter and displays their full name.

But now We want to change the behavior of method full_name. Instead of displaying only the full name of the employee, We want to display separately the first name, last name, and full name of the employee because it’s our requirement. We will change this behavior in another Python module ( main.py ) by importing the Employee class.

let’s see a quick example where we will see, with and without changing the behavior of the class.

Example:- Without changing the behavior of Module Class

employee.py

class Employee:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def full_name(self):
        print(f"Your full name will be:- {self.first_name} {self.last_name}")

main.py

# importing Employee class from employee.py
from employee import Employee

# creating object of Employee class
emp1 = Employee("Vishvajit", "Rao")
emp1.full_name()

You will execute the main.py file, you will get the following output.

Your full name is:- Vishvajit Rao

As you can see in the above output, we have got only the full name of the employee emp1 object but this is not the output that we are expecting. To get the expected output we have to apply monkey patching.

Now, it’s time to change the behavior of the method full_name of the Employee class. To change this, We need to define a function that changes the functionality of the full_name method in the employee.py file, Code of employee.py will still remain the same. We will do changes in the main.py file or module.

Example:- Changing the behavior of the Module Class

employee.py

class Employee:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def full_name(self):
        print(f"Your full name is:- {self.first_name} {self.last_name}")

main.py

from employee import Employee

def employee_full_name(self):
    print(f"Your first name is:- {self.first_name}")
    print(f"Your last name is:- {self.last_name}")
    print(f"Your full name is:- {self.first_name} {self.last_name}")


# apply monkey patching concept
Employee.full_name = employee_full_name
emp1 = Employee("John", "Doe")
emp1.full_name()

Now, when you will execute the main.py file you will get the following output.

Your first name is:- John
Your last name is:- Doe
Your full name is:- John Doe

As you can see in the above main.py code. We have defined a method employee_full_name which is responsible for displaying the first name, last name, and the full name of the emp1 object separately.

On line 10, we have applied the concept of monkey patching which means we have to change the functionality of the full_name method of the Employee class with the employee_full_name method.

So, this is how we can change the behavior of any module’s functionality using the monkey patching concept.

So far we have seen, how to change the behavior of Python functions and Python modules dynamically, Now I am going to change the behavior of Python classes dynamically.

Apply Monkey Patching on Class in Python

As we know that Python class is a mutable or mutable object which means we can change the behavior of a Python class even once it is created.

To change the functionality of the instance method, we have defined a class Student that has an instance method print_details. print_details instance method is responsible for displaying the details of any instance or object but for reason, we want to change its behavior.

For changing the behavior, we have defined another method print_student_details which takes another parameter that is the age of the student, and display a proper message as you can in the below example.

Example: Changing the behavior of Python class dynamically

class Student:

    def __init__(self, first_name, last_name, email):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

    def print_detail(self):
        print(f"My name is {self.first_name} {self.last_name} and my email is {self.email}.")


# creating object of the class student
st1 = Student("Vishvajit", "Rao", "[email protected]")
st1.print_detail()

# code to alter the instance method print_details
def print_student_details(self, age):
    print(f"My name is {self.first_name} {self.last_name}. I am {age} years old and this is email id {self.email}.")


# changing the behaviour of method print_details
Student.print_detail = print_student_details
st2 = Student("John", "Doe", "[email protected]")
st2.print_detail(24)

Output

My name is Vishvajit Rao and my email is [email protected].
My name is John Doe. I am 24 years old and this is email id [email protected].

As you can in the above example, How we have changed the existing instance method with print_student_details at run time. This is the beauty of Python monkey patching.

Important Articles:-

    Conclusion

    So, In this whole article, We have seen everything about monkey patching in Python along with a few examples. Monkey patching in Python is the most interesting thing, as a developer, we should use this concept but it is ignored by most developers.

    Now, whenever your requirement is to change the behavior of any classes, modules and functions definitely you can go with the Python monkey pathing concept.

    Let’s quickly recap this article.

    Monkey patching is a piece of code that has the capability to change the functionality of any existing Python module, class, and function at run time.

    I hope you would have understood the concept of monkey patching in Python. if you have still any confusion regarding related this monkey patching, please go to our social media handle and message us along with the problem.

    For more interesting and knowledgeable articles, please visit us.

    Thanks for your valuable time…. ❤️❤️🙏🙏

    What is frozen set in Python
    Comprehension in Python

    Related Posts