Knowledge note

Monkey-Patching

Runtime replacement, deletion, or redirection of functions, attributes, modules, or environment lookups so code executes against controlled behavior without editing the original source.

Updated September 16, 2026Confidence: High

Monkey-Patching

Monkey-Patching is runtime replacement, deletion, or redirection of functions, attributes, modules, or environment lookups so code executes against controlled behavior without editing the original source.

Why It Exists

Some code depends on global state, external services, filesystem layout, import resolution, or library internals that are inconvenient or unsafe to exercise directly. Monkey-patching lets a test or plugin intercept those lookups and substitute a controlled behavior close to the call site.

How It Works

Monkey-patching changes the object that the target code will look up at runtime. That can mean replacing a method on a class, swapping a module function, deleting a network request entry point, overriding an environment variable, or adjusting sys.path before an import happens.

In pytest, the monkeypatch fixture packages these operations behind helpers such as setattr, delattr, setitem, setenv, and syspath_prepend, then automatically undoes the changes when the test or fixture finishes. The important detail is lookup location: patch the symbol where the code under test resolves it, not merely where it was originally defined.

Tradeoffs

Monkey-patching is powerful but brittle. It depends on internal names and lookup paths staying stable, so refactors can silently break the patch. Broad patches can also hide integration problems or leak state across tests if cleanup is incomplete.

Common Confusions

  • Monkey-patching vs. dependency injection: Dependency injection changes dependencies through explicit parameters or constructors; monkey-patching changes them implicitly at runtime.
  • Monkey-patching vs. mocking: Mocking usually emphasizes test doubles and assertions about calls; monkey-patching is the mechanism that replaces the real object or behavior.
  • pytest monkeypatch vs. general monkey-patching: The pytest fixture is a disciplined helper that applies and reverts monkey-patches automatically; the broader concept is language- and framework-independent.

Where It Appears