Here’s a complete, structured guide to monkey patching in Python, covering everything from what it is and why it’s used, to risks, examples, and best practices — especially relevant when testing with tools like pytest.
Author
Benedict Thekkel
🧠 1. What is Monkey Patching?
Monkey patching is the practice of dynamically changing a class, method, or module at runtime, usually to alter or extend behavior without modifying the original source code.
✅ Often used in:
Testing/mocking
Temporary bug fixes
Dynamic feature injection
🧪 2. Monkey Patching Use Cases
Use Case
Example
Testing
Replace API calls or database functions with mocks
Hotfixes
Patch a bug in a third-party library
Instrumentation
Inject logging, metrics, or tracing code dynamically
Compatibility
Override methods for legacy or platform-specific behavior
🧩 3. Basic Monkey Patch Example
Patching a method:
class Math:def add(self, x, y):return x + y# Patch the methoddef fake_add(self, x, y):return42Math.add = fake_addm = Math()print(m.add(1, 2)) # ➜ 42
🧪 4. Monkey Patching in pytest (Using monkeypatch Fixture)
pytest provides a built-in fixture named monkeypatch to safely patch objects.