HOWTO · Python

Monkey Patching in Python

Learn what monkey patching changes at runtime, add a method to a Python class, and replace a module global safely in a pytest test.

On this page

Monkey patching changes or adds an attribute while a program is running. In Python, assigning a function to a class or replacing a name in a module changes what later attribute lookups find. This is useful for focused tests, but it can also make behavior depend on when and where the change happens.

What Monkey Patching Means in Python

Python lets programs assign attributes to many objects at runtime. Monkey patching usually means changing an existing attribute or adding one so that code uses a replacement behavior. It does not require changing the original source file, and it is not a technique exclusive to dynamic languages; other languages can provide comparable mechanisms through their own runtime or test tools.

Two cases in this guide are related but distinct. Assigning a function to a class adds behavior to instances of that class. Replacing a module global changes the value a function in that module reads when it runs. The second pattern is often useful in tests when production code uses a configured path or collaborator.

Add a Method to a Class at Runtime

When a plain function is assigned to a class, Python’s descriptor behavior binds the instance as the function’s first argument when the function is accessed through that instance. Define the function with self, then assign it to the class. This changes the existing class object; it does not create a new class.

Assigning a function to a class stores it as a descriptor. Accessing it through an instance binds that instance as the first argument, so define one parameter for self. Run this example:

class Greeter:
    pass


def greet(self, name):
    return f"Hello, {name}!"


Greeter.greet = greet
print(Greeter().greet("Ada"))
Hello, Ada!

The assignment affects Greeter and its instances in the current process. If a function is attached to a single instance instead, it is stored on that instance; it does not automatically receive the same method binding as a function found on the class. Use a class assignment when all instances should see the added method.

Patch a Module Global in a pytest Test

Suppose pipeline.py defines DATA_DIR = Path(__file__).parent / "data", and its collect_files(pattern) function returns list(DATA_DIR.glob(pattern)). The function resolves DATA_DIR in the pipeline module when it is called. Creating a temporary directory in a test does not redirect that lookup by itself, so the test must replace the name in the module where the function looks it up.

In a pytest test, tmp_path provides a temporary Path. The example below defines a small pipeline module whose collect_files function resolves DATA_DIR from that module’s namespace. Its normal data directory is empty, while the test directory contains file1.txt. Before patching, assert pipeline.collect_files("*.txt") == [expected_file] would fail: the comparison is [] == [expected_file]. After monkeypatch.setattr, the function returns the file from the test directory. This describes the deterministic failure for the shown setup; it is not a captured pytest run.

from pathlib import Path
import tempfile
import types


pipeline = types.ModuleType("pipeline")
production_data = tempfile.TemporaryDirectory()
pipeline.DATA_DIR = Path(production_data.name)
exec(
    "def collect_files(pattern):\n"
    "    return list(DATA_DIR.glob(pattern))\n",
    pipeline.__dict__,
)


def test_collect_files_uses_temporary_data(tmp_path, monkeypatch):
    test_data = tmp_path / "data"
    test_data.mkdir()
    expected_file = test_data / "file1.txt"
    expected_file.write_text("sample", encoding="utf-8")

    files_before_patch = pipeline.collect_files("*.txt")
    assert files_before_patch == []

    monkeypatch.setattr(pipeline, "DATA_DIR", test_data)
    assert pipeline.collect_files("*.txt") == [expected_file]

The patch target matters: patch pipeline.DATA_DIR, because collect_files looks up that module global. Patching a similarly named variable in the test module does not change the global used by pipeline.collect_files. The fixture name is monkeypatch, and monkeypatch.setattr is the operation that replaces the attribute. Pytest restores the original value after the test, including when the test fails, which helps keep the change scoped to that test. The fixture manages the replacement; it does not make the test’s temporary files or directory automatically become the module’s data directory.

Use Monkey Patching Carefully

Monkey patching is useful when a test needs to replace a dependency or redirect a module-level setting without changing the production call path. Keep the replacement local to the test, target the name the code actually reads, and prefer pytest’s monkeypatch fixture so the original attribute is restored after the test.

Changes to shared classes or modules can affect unrelated code that runs later, and the result may depend on import order or test order. Avoid permanent application-wide patches when ordinary configuration, dependency injection, or a small wrapper function would make the dependency explicit. A class patch is appropriate when the added method should be visible to instances of that class; a module-global patch is appropriate when a function reads a module-level name that a test needs to replace. These distinctions make failures easier to diagnose and reduce surprising behavior.