What is monkey patching in Python and should you use it
· Category: Python Programming
What is monkey patching in Python and should you use it
Definition
Monkey patching is the practice of modifying or extending code at runtime without altering the original source. In Python, this usually means reassigning methods or attributes on classes or modules.
Example
class Dog:
def bark(self):
return "Woof"
# Monkey patch at runtime
Dog.bark = lambda self: "Meow"
d = Dog()
print(d.bark()) # Meow
Common Use Cases
Monkey patching appears most often in testing, where external dependencies are stubbed:
import requests
def mock_get(url, **kwargs):
class MockResponse:
status_code = 200
def json(self):
return {"mocked": True}
return MockResponse()
requests.get = mock_get
For safer testing patterns, consider Python testing with pytest and its built-in monkeypatch fixture. If you need to swap behavior cleanly in production, Python decorators explained offer a more maintainable approach.
Should You Use It?
Avoid monkey patching in production code. It harms readability, breaks encapsulation, and can cause subtle bugs when libraries update. Prefer composition, dependency injection, or official extension points.