Monkey patching modifies code at runtime; it is powerful but risky and hard to maintain
Monkey patching is the practice of modifying a module, class, or function at runtime, usually to change behavior without editing the original source. In Python, you can assign to module attributes, class attributes, or instance attributes to replace methods or add new ones. It is sometimes used in testing to mock dependencies, in frameworks like gevent to patch blocking IO, or as a quick hotfix. The risks are significant: it makes code unpredictable because behavior depends on import order and runtime state; it can break other libraries that rely on the original implementation; it is hard to debug because the source code does not reflect the actual behavior; and it can break across versions when the patched internals change. In production, monkey patching should be a last resort. Prefer subclassing, dependency injection, decorators, or configuration. If you must patch, isolate it, document it, and test it thoroughly.
Monkey patching changes behavior globally for the process, affecting all code that uses the patched object.
It breaks assumptions about modules and classes, making debugging and reasoning difficult.
It can conflict with other patches and with library upgrades.
Acceptable uses: testing with mocks, compatibility shims for old versions, and some framework integrations.
Alternatives: subclassing, composition, dependency injection, decorators, and configuration flags.
Common mistake: patching a third-party library globally in production to fix a bug, then forgetting about it.
Common mistake: patching without restoring the original, causing test pollution.
Version note: unittest.mock.patch is the safe, scoped way to monkey patch in tests.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience