Home > Software engineering >  Replacing function of a module with a custom one
Replacing function of a module with a custom one

Time:11-19

I am working with an external module with a class A and function foo. The class calls the function inside it

def foo(...):
    ...

class A:
  def m(self, ...):
      ...
      foo()
      ...
  ...

I need to change the behavior of foo without editing the module. Is there a neat way to do it, without subclassing class A?

CodePudding user response:

Define the replacement function, then assign it to the class function.

def replacement_m(...):
    ...

from external_module import A
A.m = replacement_m

Unfortunately you can't just replace foo(), because it isn't a class method. You have to replace the whole A.m method.

This is called monkeypatching. See this question for more information What is monkey patching?

  • Related