Monkey Patching in Python: A Powerful Yet Controversial Technique

Author: neptune | 01st-Aug-2023

Monkey patching is a technique in Python that allows you to dynamically modify or extend the behaviour of a module, class, or function at runtime. It gives you the ability to alter the behaviour of existing code without modifying the original source code. While monkey patching can be a powerful tool, it should be used judiciously, as it can lead to unexpected consequences and make the codebase harder to maintain and understand.

Understanding Monkey Patching

At its core, monkey patching involves replacing or modifying attributes, methods, or functions of an object or module to change its behaviour. It allows you to add or override functionalities without touching the original source code, making it useful for temporary fixes or adding features to third-party libraries.

Examples of Monkey Patching

Let's go through some examples to understand how monkey patching works.

Example 1: Patching a Function

Suppose we have a simple function that adds two numbers:

def add(a, b):

    return a + b

Now, let's monkey patch the `add` function to always return 10, regardless of the input:

def patched_add(a, b):

    return 10

add = patched_add

result = add(5, 7)

print(result# Output: 10

In this example, we replaced the `add` function with our `patched_add` function using assignment.

Example 2: Patching a Method

Let's consider a class `Calculator` with a method `multiply`:

class Calculator:

    def multiply(self, a, b):

        return a * b

calc = Calculator()

result = calc.multiply(3, 4)

print(result# Output: 12

Now, we'll monkey patch the `multiply` method to always return 100:

def patched_multiply(self, a, b):

    return 100

Calculator.multiply = patched_multiply

result = calc.multiply(3, 4)

print(result# Output: 100

In this example, we modified the `multiply` method of the `Calculator` class to use our custom `patched_multiply` function.

When to Use Monkey Patching

While monkey patching can be useful for temporary fixes or quick prototyping, it is generally not recommended for production code or library development. Here are some scenarios where monkey patching may be appropriate:

1. Testing: In unit tests, monkey patching can be used to replace external dependencies with mock objects for isolated testing.

2. Debugging: Temporary patches can be applied during debugging to trace issues or validate potential solutions.

3. Third-party Libraries: When dealing with unmodifiable third-party code, monkey patching can help add missing features or fix bugs.

Risks and Pitfalls

It is essential to be cautious when using monkey patching, as it can introduce several risks and pitfalls:

1. Maintainability: Monkey patched code can be hard to maintain, as it hides changes and may cause confusion for other developers.

2. Compatibility: Updates or changes to the patched code could lead to unexpected behaviour or conflicts with future releases.

3. Debugging Nightmares: Debugging monkey-patched code can become a nightmare, especially when multiple patches interact.

4. Collisions: Multiple patches applied to the same codebase can lead to conflicts and unpredictable behaviour.


Monkey patching can be a powerful technique in Python, offering the ability to modify code at runtime without altering the original source. However, it should be used sparingly and with caution. It is best suited for testing, debugging, and temporary fixes, but not for long-term production code or library development. Always strive for clean and maintainable code to avoid potential issues down the line.

Related Blogs
How to extract Speech from Video using Python?
Author: neptune | 16th-Jun-2023
#Python #Projects
Simple and easy way to convert video into audio then text using Google Speech Recognition API...

How to download video from youtube using python module ?
Author: neptune | 15th-Jun-2023
We will let you know how you can easily download the Youtube high quality videos along with subtitle, thumbnail, description using python package..

Best Python package manager and package for virtual environment ?
Author: neptune | 18th-Jun-2023
#Python #Pip
We will explore the options of Pip, Virtualenv, Anaconda, and also introduce Pyenv as a helpful tool...

Deploy Django project on AWS with Apache2 and mod_wsgi module.
Author: neptune | 25th-May-2023
#Python #Django
In this blog I use the AWS Ubuntu 18.22 instance as Hosting platform and used Apache2 server with mod_wsgi for configurations. We create a django sample project then configure server...

Mostly asked Python Interview Questions - 2023.
Author: neptune | 30th-May-2023
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...

How to reverse string in Python ?
Author: neptune | 16th-May-2022
We are going to explore different ways to reverse string in Python...

Python Built-in functions lambda, map, filter, reduce.
Author: neptune | 15th-Jun-2023
We are going to explore in deep some important Python build-in functions lambda, map, filter and reduce with examples...

Core Python Syllabus for Interviews
Author: neptune | 26th-Jul-2023
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...

Python 3.9 new amazing features ?
Author: neptune | 26th-Jul-2023
Python 3.9 introduces new features such as dictionary union, string methods to remove prefixes and suffixes, type hinting, and speed improvements for built-in functions...

Input and Output in Python
Author: neptune | 13th-Jul-2023
In this article, we will see how Python take input from user and How it display the output to user. First we cover input then output...

5 Best Python Testing Frameworks.
Author: neptune | 12th-Apr-2023
#Python #Testing
Python offers various testing frameworks, including Pytest, unittest, Nose, Robot Framework, and Behave, to build robust and reliable software...

5 Languages that Replace Python with Proof
Author: neptune | 13th-Apr-2023
Julia, Rust, Go, Kotlin, and TypeScript are modern languages that could replace Python for specific use cases...

10 Proven Ways to Earn Money Through Python
Author: neptune | 11th-Apr-2023
Python offers numerous earning opportunities from web development to teaching, data analysis, machine learning, automation, web scraping, and more...

View More