Monkey patching is when you change code at runtime instead of editing the original source file.
Basically, you take an existing class, function, or module and swap in new behavior while the program is already running.
This shows up a lot in dynamic languages like Python, Ruby, and JavaScript.
Why Use It
- Fix a bug in a library without waiting for the library to update
- Add behavior to code you do not own
- Mock or replace something during tests
Example
In Python, you could replace a method on a class:
class Dog:
def speak(self):
return "woof"
def new_speak(self):
return "bark bark"
Dog.speak = new_speak
print(Dog().speak()) # bark barkNow every Dog uses the patched version of speak.
Caution
Monkey patching is useful, but it can make code confusing because the behavior is no longer only defined where the original code lives.
It is best for small fixes, tests, or temporary workarounds. If it becomes a core part of the app, it usually deserves a cleaner design.