What Is Monkey Patching in Python and When Is It Appropriate?
Learn what monkey patching is in Python, how unittest.mock.patch uses it safely for testing, and why it is risky and fragile in production codebases.
Expected Interview Answer
Monkey patching is dynamically modifying or replacing a class or module's attributes, methods, or functions at runtime, without changing the original source code.
Because Python classes and modules are just objects whose attributes can be reassigned, you can do something like `SomeClass.method = new_function` to swap behavior after the class is already defined and imported elsewhere. It's commonly used in testing to mock out a dependency (e.g. replacing a function that calls an external API), or as a quick fix for a bug in a third-party library you can't edit directly. It's considered risky in production code because it makes behavior implicit and hard to trace, can silently break if the library changes, and can cause confusing bugs if applied inconsistently across a codebase.
- Lets tests replace real dependencies with controllable mocks
- Enables quick, temporary fixes to third-party bugs
- Useful for adding instrumentation without editing source
- Works because classes/modules are ordinary mutable objects
- unittest.mock.patch provides a safe, scoped way to do it
AI Mentor Explanation
Monkey patching is like swapping a team's usual wicketkeeper gloves for a specialized pair mid-tour without telling the manufacturer — the player still wears 'the gloves' by name, but the gear behind that name has quietly changed. It works for one tour's need, but if nobody documents the swap, a future coach expecting the standard-issue gloves gets confused by unexpected grip behavior.
Step-by-Step Explanation
Step 1
Classes/modules are mutable objects
Because everything in Python is an object, you can reassign an attribute on a class or module after it's defined.
Step 2
Replace the attribute
SomeClass.method = new_function swaps behavior for every instance using that class from that point on.
Step 3
Common use: testing
unittest.mock.patch temporarily replaces a dependency during a test, then restores the original afterward.
Step 4
Common use: hotfixes
Patching a third-party library's buggy method at runtime without forking or editing its source.
Step 5
Risk: implicit, fragile behavior
Patches can silently break on library upgrades and make debugging harder since behavior no longer matches the source code.
What Interviewer Expects
- Explains monkey patching as runtime modification of classes/modules
- Gives a concrete use case, especially testing with mock.patch
- Acknowledges the risks: fragility, hidden behavior, debugging difficulty
- Knows patches should be scoped and reverted (as mock.patch does automatically)
- Distinguishes monkey patching from normal subclassing or composition
Common Mistakes
- Presenting monkey patching as a good general-purpose design tool rather than a targeted workaround
- Not mentioning unittest.mock.patch as the standard safe mechanism
- Forgetting patches can conflict if applied by multiple parts of a codebase
- Confusing monkey patching with proper extension mechanisms like subclassing
Best Answer (HR Friendly)
“Monkey patching means changing how existing code behaves at runtime, without touching its original source file — often used in tests to fake a dependency, or as a temporary fix for a bug in a library you can't edit. It's powerful but risky if overused, since it makes behavior harder to trace.”
Code Example
from unittest.mock import patch
import requests
def get_status(url):
return requests.get(url).status_code
def fake_get(url):
class FakeResponse:
status_code = 200
return FakeResponse()
with patch("requests.get", side_effect=fake_get):
print(get_status("https://example.com")) # 200, no real network call
# Manual monkey patch (use sparingly)
# requests.get = fake_getFollow-up Questions
- How does unittest.mock.patch make monkey patching safer for tests?
- What are the risks of monkey patching in production code?
- How does monkey patching differ from subclassing or composition?
- Can monkey patching be scoped to avoid affecting the whole program?
- When would you monkey patch a third-party library versus forking it?
MCQ Practice
1. What is monkey patching?
Monkey patching replaces attributes, methods, or functions on an existing class or module while the program is running.
2. What is a common safe use of monkey patching?
unittest.mock.patch scopes a monkey patch to a test and automatically restores the original behavior afterward.
3. What is a key risk of monkey patching?
Because the patch changes behavior outside the original source, it becomes harder to trace and can break unexpectedly if the patched code changes.
Flash Cards
What is monkey patching? — Dynamically changing a class/module's attributes or methods at runtime.
What's the safe standard way to monkey patch in tests? — unittest.mock.patch, which auto-restores the original after the test.
Why is monkey patching risky in production? — It makes behavior implicit, hard to trace, and fragile to library changes.
What's a legitimate use case? — Mocking dependencies in tests or applying a temporary hotfix to a third-party bug.