Software Technology Tips

Monkey patching a way of programming in which we can modify or extend the executing code at runtime. This is offered in some dynamic typing languages like javascript, perl, python etc. This can be scary in a production environment because it is very difficult to debug this kind of code, but this can be very useful in some situation like testing. We are going through an issue that is happening in a server deployment, but that is working fine in the dev environment. Moreover we can't put the source code there and debug or put some break point and watch different variables, because the libraries are proprietary, so in this situation monkey patching is to our rescue, we can add some logging dynamically to the source code and track what is going on.
How to do monkey patching in python, lets say we have a class Foo with bar method in it in module baz.

class Foo(object):
   def bar(self):
      bar body

Now from outside, I can define a function monkey_bar
def monkey_bar(self):
   monkey_bar body

Now I can modify the content of bar dynamically and run as below:
import baz = monkey_bar
new_obj = baz.Foo()

There is a saying in python world about the dynamic typing/ duck typing "If it walks like a duck and quacks like a duck, it is a duck". With this we can say "Go on puching until it walks and quacks like a duck :)".

Related Tags:

Python, Monkey Patching

Author: Bimal Biswal


Let us Connect!

Awards and Achievements

Red Herringcolor DeloitteFast50 DB ZInnov1   Nascome  DB Stpi

This site uses cookies. We respect your privacy.copyright (c) Mindfire Solutions 2007-2015. Login