Fix python object to add default value to kwargs method

I want to fix some code that uses an object from an external module.

One method of this object is called universally, and I need to set a new default kwarg in all these calls.

Instead of adding as many duplicates of the code, I thought it would be better to change the method of the object. What is the cleanest way to do this?

+4
source share
2 answers

This is called monkey clearance , and there is no "clean" version.

If you need to replace a method barin a class Foo, use this code:

oldMethod = Foo.bar
def newMethod(self, **kwargs):
    ... fix kwargs as necessary ...
    oldMethod(self, **kwargs)
Foo.bar = newMethod
  • First, we store the old method handle in a variable
  • . self, .
  • , oldMethod(self, ...). . self.oldMethod() , class ( ).
  • , .

:

+3

-, , .

class Wrapper(Target):
    def method(self, *args, **kwargs):
        kwargs['option'] = True
        return super(Wrapper, self).method(*args, **kwargs)

instance = Target()
instance.__class__ = Wrapper
0

Source: https://habr.com/ru/post/1570023/


All Articles