Python Monkey Patching


  
Every thing in python is OBJECTS...

Modify your class/function behaviour which you ve written or which u ve imported by modules just like that...

Modification will not affect source class or mudle insted requirement served at run time.

Below is the example


  1 class foo:
  2
  3     def bar(self):
  4         print "Original function Bar()"
  5
  6     def bar_two(self):
  7         print "Original function Bar_two()"
  8
  9 if __name__ == "__main__":
 10
 11     foo_obj = foo()
 12
 13     def monkey_patch():
 14         print "This is patched mokey code"
 15
 16     foo_obj.bar = monkey_patch
 17     print "---- Verify bar() in class foo -----"
 18     foo_obj.bar()
 19     print "---- Verify bar_two() in class foo -----"
 20     foo_obj.bar_two()

In the above example when you call (line 18)
     foo_obj.bar()    actually method "bar" prints "Original function Bar()"

Because of monkey patching in line 16
     foo_obj.bar = monkey_patch   actual bar object was replaced with 
monkey_patch object.