Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patch a python object to add default to method kwargs

Tags:

python

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?

like image 977
so12311 Avatar asked Oct 19 '22 19:10

so12311


1 Answers

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
  1. First, we save the old method handle in a variable
  2. Then we define the new method as a function. The first argument has to be self, just as if this function was inside of a class.
  3. To call the original method, we use 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).
  4. Lastly, we install the patched method in the class.

Related:

  • http://mflerackers.wordpress.com/2012/02/01/modifying-python-classes-at-run-time/
like image 102
Aaron Digulla Avatar answered Oct 23 '22 01:10

Aaron Digulla