Python Monkey Patching: The Magic of Replacing Behaviour at Runtime

This article explains how monkey patching replaces attributes of modules and classes at runtime, why a name must be patched where it is looked up, and how unittest.mock applies and restores patches safely in tests.

A green snake coiled over a weathered branch, its head turned sideways against a dark background.
Photo by Eric DSK on Unsplash

In Python, modules, classes and functions are ordinary objects whose attributes can be reassigned while the program runs, so the behaviour of code written by someone else can be changed without editing its source file. This technique is known as monkey patching. It is indispensable in tests, where a network call or a clock must be replaced by a predictable substitute, and it is risky in application code, where the change is invisible to every other reader of the program. The present article examines how an attribute is replaced at runtime, why the place where a name is looked up decides whether a patch has any effect, how unittest.mock applies and removes patches safely, and which alternatives make patching unnecessary. A patch that is applied precisely and removed reliably is the secret weapon of every test suite that depends on external systems.

Replacing Attributes at Runtime

A module is an object, and each function it defines is an attribute of that object. Assigning a new value to the attribute changes what every later lookup through the module returns, as the following example shows with the function json.dumps of the standard library.

import json

original_dumps = json.dumps

def compact_dumps(obj, **kwargs):
    return original_dumps(obj, separators=(",", ":"), **kwargs)

json.dumps = compact_dumps
print(json.dumps({"id": 7, "tags": ["a", "b"]}))  # Output: {"id":7,"tags":["a","b"]}

json.dumps = original_dumps
print(json.dumps({"id": 7, "tags": ["a", "b"]}))  # Output: {"id": 7, "tags": ["a", "b"]}

The replacement keeps a reference to the original function, both to delegate to it and to restore it afterwards. While the patch is active, it affects every module of the program that calls json.dumps, not only the module that applied it, which is the source of both the usefulness and the danger of the technique.

Classes can be patched in the same way, with one difference that comes from attribute lookup. A function assigned to a class becomes a method for every instance, including those created before the patch, whereas a function assigned to a single instance is not bound and affects that instance only, a distinction that follows from the descriptor protocol examined in the article devoted to descriptors.

class Greeter:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return "hi"

ada = Greeter("Ada")
Greeter.greet = lambda self: f"hello, {self.name}"
print(ada.greet())                          # Output: hello, Ada

ada.greet = lambda: "instance only"
print(ada.greet(), Greeter("Bob").greet())  # Output: instance only hello, Bob

try:
    str.upper = lambda text: text
except TypeError as error:
    print(error)  # Output (CPython 3.12): cannot set 'upper' attribute of immutable type 'str'

The instance-level function receives no self, because functions stored in an instance are not turned into methods. The last lines show the limit of the technique: built-in types such as str, int or list are immutable, so their methods cannot be replaced at all.

Where the Name Is Looked Up

A patch replaces one reference, namely the attribute of one object, and it has no effect on other references to the same function. The statement from math import sqrt copies a reference into the importing module, so patching math.sqrt afterwards leaves that copy untouched. The documentation of unittest.mock summarizes the rule in its section "Where to patch": the name must be patched where the code under test looks it up, not where it is defined.

import math
from math import sqrt
from unittest import mock

def hypotenuse_module(a, b):
    return math.sqrt(a * a + b * b)

def hypotenuse_imported(a, b):
    return sqrt(a * a + b * b)

with mock.patch("math.sqrt", return_value=0.0):
    print(hypotenuse_module(3, 4))    # Output: 0.0
    print(hypotenuse_imported(3, 4))  # Output: 5.0

with mock.patch("__main__.sqrt", return_value=0.0):
    print(hypotenuse_imported(3, 4))  # Output: 0.0

The first function reads sqrt through the module math at every call and sees the patch; the second reads its own global name and does not. The example runs as a script, so the importing module is __main__; in a project, a module report that contains from math import sqrt requires the target "report.sqrt". This rule explains most of the patches that appear to be applied correctly and yet change nothing.

Save Point: Patches That Restore Themselves

The module unittest.mock, part of the standard library since Python 3.3, provides patch, which replaces an attribute with a mock object and restores the original when the patch ends, even if the code inside raises an exception. It can be used as a context manager, as a decorator or with explicit start() and stop() calls; its decorator form follows the mechanism described in the article devoted to decorators. The following example tests a function that checks a website through urllib.request, without any network access.

import urllib.error
import urllib.request
from unittest import mock

def website_status(url):
    try:
        with urllib.request.urlopen(url, timeout=5) as response:
            return f"up ({response.status})"
    except urllib.error.URLError as error:
        return f"down ({error.reason})"

with mock.patch("urllib.request.urlopen") as fake_urlopen:
    fake_urlopen.return_value.__enter__.return_value.status = 200
    print(website_status("https://example.com"))  # Output: up (200)
    fake_urlopen.assert_called_once_with("https://example.com", timeout=5)

@mock.patch("urllib.request.urlopen", side_effect=urllib.error.URLError("refused"))
def check_failure(fake_urlopen):
    return website_status("https://example.com")

print(check_failure())                                # Output: down (refused)
print(isinstance(urllib.request.urlopen, mock.Mock))  # Output: False

The mock records how it was called, so the test verifies both the result and the arguments, including the timeout. The attribute side_effect makes the mock raise an exception, which simulates a failure that would be difficult to provoke with a real server. The last line confirms that the original urlopen is back in place once both patches have ended. Related helpers cover other targets: patch.object patches an attribute of an object already at hand, and patch.dict changes a dictionary, such as os.environ, for the duration of the patch.

A plain mock accepts any call, which hides a test that calls the replaced function with the wrong arguments. The option autospec=True, or the function create_autospec, builds a mock with the signature of the real object, as the following example shows.

import os
from unittest import mock

def apply_discount(price, rate):
    return price * (1 - rate)

loose = mock.Mock(return_value=90.0)
print(loose(100))  # Output: 90.0

strict = mock.create_autospec(apply_discount, return_value=90.0)
try:
    strict(100)
except TypeError as error:
    print(error)  # Output: missing a required argument: 'rate'

with mock.patch.dict(os.environ, {"APP_MODE": "test"}):
    print(os.environ["APP_MODE"])  # Output: test
print("APP_MODE" in os.environ)    # Output: False

The loose mock accepts a call that the real function would reject, while the autospecced mock raises the same TypeError as the function. The final lines show patch.dict restoring the environment, assuming that APP_MODE was not defined before the example ran.

Pitfalls of Monkey Patching

Monkey patching changes shared state, and most of its failures come from changes that last longer, or reach further, than intended. Five pitfalls are distinguished, which are the following:

  1. Patches that are never removed. A manual patch without try/finally stays active when the test fails, and every later test runs against the replacement.
  2. Patching the wrong name. A function imported with from module import name must be patched in the importing module.
  3. Global reach. A patch applied in application code changes the behaviour for every module of the program, including libraries that rely on the original.
  4. Silent signature drift. A plain mock accepts any arguments, so a test keeps passing after the real function changes its signature; autospec prevents it.
  5. Fragility across versions. A patch of private or internal functions of a library breaks, sometimes silently, when the library is updated.

The first pitfall, which affects the manual technique of saving and restoring an attribute, is reproduced in the following example.

import json

def broken_test():
    original = json.dumps
    json.dumps = lambda obj: "fake"
    assert json.dumps({}) == "expected"  # Fails and leaves the function.
    json.dumps = original                # Never reached.

try:
    broken_test()
except AssertionError:
    print("test failed")  # Output: test failed
print(json.dumps({}))     # Output: fake

The failed assertion skips the restoring line, so the fake function remains in json after the test has finished. A patch used as a context manager or decorator, or a manual patch inside try/finally, does not have this problem.

Choosing the Right Tool

Consequently, monkey patching is a tool for controlling dependencies that the code does not receive explicitly, and the following table summarizes when each form is appropriate.

Need Recommended approach
Replace a dependency during a test unittest.mock.patch as context manager or decorator
Replace an attribute of an object at hand mock.patch.object
Change environment variables or a dictionary temporarily mock.patch.dict
Keep the mock faithful to the real signature autospec=True or create_autospec
Change behaviour in application code Pass the behaviour as an argument or a strategy object instead of patching
Fix a bug in a third-party library A documented, version-checked patch applied once at startup, until the fix is released
Methods of str, int, list and other built-in types Not patchable; wrap the value or use a subclass

Passing behaviour explicitly, as in the article devoted to the Strategy pattern, makes the replacement visible in the signature of the code and removes the need to patch it in tests.

Conclusion

It is concluded that monkey patching relies on a simple property of Python, namely that modules and classes are objects whose attributes can be reassigned, and that its correct use depends on two details: patching the name where the code looks it up, and guaranteeing that the original is restored. The module unittest.mock provides both guarantees, together with mocks that record their calls and respect the signature of the real object. This magic belongs mainly to tests; in application code, a dependency that must change is better received than replaced. Dependency injection, which turns that principle into a design technique, is developed in a future article of this series.