💡 Advanced Python Concepts
Estimated reading: 4 minutes 109 views

🛠️ Python Monkey Patching – Dynamically Modify Code at Runtime

🧲 Introduction – What Is Monkey Patching?

Monkey patching is a dynamic technique where you change classes, methods, or functions at runtime—without modifying the original source code.

It’s often used for:

  • Fixing bugs in third-party libraries
  • Adding behavior to modules you can’t edit
  • Creating test doubles or mocks in unit testing
  • Quick prototyping in dynamic environments

⚠️ While powerful, monkey patching can lead to hard-to-trace bugs, so it should be used with caution.

🎯 In this guide, you’ll learn:

  • What monkey patching is and how it works
  • When and why to use it
  • Real-world examples including standard library patching
  • How it’s used in testing
  • Best practices and caveats

✅ What Is Monkey Patching in Python?

Monkey patching is the act of changing or extending existing code at runtime—typically by overriding methods or attributes.

Python allows it easily because everything (functions, methods, classes) is dynamic and mutable.


🧪 Simple Monkey Patch Example

class Dog:
    def speak(self):
        return "Woof"

def new_speak():
    return "Meow 🐱"

Dog.speak = new_speak

d = Dog()
print(d.speak())  # Meow 🐱

✅ The speak() method was replaced at runtime.


🔄 Monkey Patching Built-in Modules

import time

def fake_sleep(seconds):
    print(f"[Skipping sleep for {seconds} seconds]")

time.sleep = fake_sleep

time.sleep(5)  # [Skipping sleep for 5 seconds]

✅ Used in testing to skip real-time delays.


🧰 Real-World Use Case – Patching requests.get()

import requests

def fake_get(url):
    class FakeResponse:
        def json(self):
            return {"message": "fake response"}
    return FakeResponse()

requests.get = fake_get

res = requests.get("https://api.example.com")
print(res.json())  # {'message': 'fake response'}

💡 Used to mock external APIs in tests or sandbox environments.


🧪 Monkey Patching in Tests (Preferred: patch())

Instead of patching manually, use unittest.mock.patch() for temporary and safe monkey patches:

from unittest.mock import patch

def get_data():
    return "real data"

@patch('__main__.get_data', return_value="mocked data")
def test_func(mock_func):
    print(get_data())  # mocked data

test_func()
print(get_data())  # real data

✅ The patch is automatically reverted after the test.


🚨 Risks of Monkey Patching

RiskDescription
Hard to debugModified behavior may not be obvious
Breaks compatibilityUpstream code changes may conflict with patch
Non-reversibleManual patches are global and persistent
Affects all importsPatching affects all modules using the target

📘 Best Practices

✅ Do This❌ Avoid This
Use unittest.mock.patch() for testsPatching modules manually in tests
Document every patch clearlyLeaving patches undocumented
Isolate patches to smallest scopePatching globally in large applications
Revert or restore original methodsForgetting to unpatch in production
Patch only when other options are blockedPatching when subclassing is cleaner

📦 Alternative to Monkey Patching

TechniqueUse When
SubclassingYou own the class and can inherit cleanly
DecoratorsYou want to wrap functions without changing them
Dependency InjectionYou want to pass behaviors as arguments
Test mockingYou’re writing unit tests

📌 Summary – Recap & Next Steps

Monkey patching is a powerful tool that lets you change code at runtime—but with great power comes great responsibility. Use it sparingly, and always document its purpose.

🔍 Key Takeaways:

  • ✅ Monkey patching changes behavior at runtime without modifying the original source
  • ✅ It’s great for quick fixes, mocking, and testing
  • ✅ Use unittest.mock.patch() for safe, temporary patches
  • ❌ Avoid monkey patching when subclassing or dependency injection is a better alternative

⚙️ Real-World Relevance:
Used in testing frameworks, hotfixes in production, plugin systems, and dynamic runtime behavior.


❓ FAQ – Python Monkey Patching

❓ What is monkey patching?

✅ It’s dynamically modifying or replacing classes, methods, or functions at runtime.

❓ Is monkey patching safe?

⚠️ It can be useful but risky. Always document it, and use temporary patches when possible (e.g. in tests).

❓ Can I undo a monkey patch?

✅ Only if you store the original method and restore it manually:

original = time.sleep
time.sleep = fake_sleep
time.sleep = original

❓ Is monkey patching allowed in production?

❌ Generally discouraged. Use only for urgent fixes and prefer clean design alternatives.

❓ How is monkey patching different from mocking?

  • Monkey patching: manual, global, often permanent
  • Mocking: temporary, scoped (especially via patch()), designed for testing

Share Now :
Share

Python Monkey Patching

Or Copy Link

CONTENTS
Scroll to Top