I want to patch some code that uses an object from an external module.
One method of this object is called all over the place, and I need to set a new default kwarg in all those calls.
Rather than add so much duplicate code, I thought it would be better to change the object method. What is the cleanest way to do this?
This is called monkey-patching and there is no "clean" version of it.
If you need to replace a method bar
in a class Foo
, use this code:
oldMethod = Foo.bar
def newMethod(self, **kwargs):
... fix kwargs as necessary ...
oldMethod(self, **kwargs)
Foo.bar = newMethod
self
, just as if this function was inside of a class.oldMethod(self, ...)
. This will take the method pointer, and call it with the instance as first argument. self.oldMethod()
doesn't work since we're not in a class
context (I think).Related:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With