0

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?

aretor
  • 2,379
  • 2
  • 22
  • 38

1 Answers1

2

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?

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • Considering that `foo()` can be seen as a module variable, can't I perform something similar to `module.foo = replacement_foo`? – aretor Nov 17 '21 at 08:45
  • Confirmed. I can perform the same monkey patching directly on a global function of a module (`foo` in my case). This changes the behavior of all class instances, also those that were istantiated *before* the patching. – aretor Nov 17 '21 at 10:02
  • @aretor Thanks for the info! – John Gordon Nov 18 '21 at 15:45