17. Monkey Patching

Monkey Patching refers to the practice of dynamically changing or modifying a class or module's behavior during runtime. This technique can be used to fix bugs, add new features, or extend functionality without altering the original code directly.


1. Basic Monkey Patching of a Function

Copy

# Original function
def greet(name):
    return f"Hello, {name}"

# Monkey patching the function
def new_greet(name):
    return f"Hi, {name}"

greet = new_greet  # Replace the original function with the new one

# Test the patched function
print(greet("John"))  # Output: Hi, John

2. Monkey Patching a Method of a Class

Copy

class Dog:
    def speak(self):
        return "Woof"

# Monkey patch the speak method
def new_speak(self):
    return "Bark"

Dog.speak = new_speak  # Replace the speak method

# Test the patched method
dog = Dog()
print(dog.speak())  # Output: Bark

3. Monkey Patching a Module Function

Copy


4. Monkey Patching for Logging

Copy


5. Monkey Patching for Debugging

Copy


6. Monkey Patching to Extend Behavior

Copy


7. Monkey Patching to Handle Errors

Copy


8. Monkey Patching with a Wrapper

Copy


9. Monkey Patching a Class Constructor

Copy


10. Monkey Patching for Performance

Copy


Notes:

  1. Caution: While monkey patching is powerful, it can also lead to maintenance challenges, especially when debugging or upgrading libraries. It can cause unexpected behaviors if not used carefully.

  2. Use Cases: Monkey patching is often used in testing, bug fixes, and adding features to third-party libraries without modifying their source code.

  3. Alternative: Instead of monkey patching, consider subclassing or using decorators for more controlled modifications.

Last updated