Search code examples
pythonmonkeypatching

Monkey-patching a method of an instance with hierarchical inheritance


Imagine example below:

class Parent():
    def foo():
        ...

def Child(Parent):
    def foo():
        ... # some stuff
        super().foo()
        ... # some stuff

obj1 = Parent()
obj2 = Child()

patched_foo():
    ...

I'm trying to monkey-patch the foo method from the Parent class in instances (and not the classes). I'm currently doing below:

import types

def monkey_patch(x):
    if isinstance(x, Parent):
        x.foo = types.MethodType(patched_foo, x)

This works fine with obj1 but not for obj2 where the foo method of Parent is overwritten. Is there a way to get access and patch the foo from Parent? Perhaps somehow using super()?


Solution

  • super() is retrieving the method from the parent class object, of which there is only one. You can patch the method on that class, but the change will be felt by all instances of the parent class and its descendants. You can't patch on an individual instance.