🐒 Monkey Patching with Context Managers — Python Clean Hack

Welcome to the world of Monkey Patching 🐒 + Context Managers.

🐍 What is Monkey Patching?

Monkey Patching is simply dynamically replacing a method or attribute of a module/class at runtime.

Example:

import math

# Patch math.sqrt
math.sqrt = lambda x: "Hacked!"

print(math.sqrt(9))  # Outputs: Hacked!

🎯 Problem:

But what if you only want this patch to happen temporarily in a specific block of code? You don’t want to break other parts of the codebase.

✅ Solution: Context Manager + Monkey Patch

Using contextlib.contextmanager, you can create a scoped patch that:

  1. Applies the patch.
  2. Runs your code.
  3. Reverts the patch.

💡 Minimal Example:

from contextlib import contextmanager

def new_sqrt(x):
    print(f"Pretending to compute sqrt of {x}")
    return 42  # Totally wrong, but fun!

@contextmanager
def monkey_patch_sqrt():
    import math
    original_sqrt = math.sqrt  # Save original
    math.sqrt = new_sqrt       # Monkey-patch
    try:
        yield
    finally:
        math.sqrt = original_sqrt  # Revert patch

# Usage:
import math

print(math.sqrt(9))  # Normal behavior: 3.0

with monkey_patch_sqrt():
    print(math.sqrt(9))  # Patched behavior: Pretending to compute sqrt of 9 → 42

print(math.sqrt(9))  # Back to normal: 3.0

🧠 What’s Happening?

  • Before the with block: math.sqrt works as usual.
  • Inside the with block: math.sqrt is replaced with new_sqrt.
  • After the block: The original math.sqrt is restored.

🔥 When to Use This?

  • Temporary Bug Fixes in libraries.
  • Behavior Mocking during tests.
  • Experimenting with library internals.
  • Quick hacks without touching external code.

🚀 Pro Tip:

This trick works for any class method, module function, or attribute in Python.

TL;DR:

Monkey patch + context manager = Safe, Scoped Overrides in Python 🐍🔧.

Happy codding!

Alejandro Martínez León
Alejandro Martínez León
PhD-Student in Biophysics

My research interests include molecular dynamic simulations, coding and theoretical biophysics.