Monkey patching in python

I was just reading an article about Martijn Pieters, who is a python expert, and he mentioned
monkey patching

I did not know what monkey patching is, so I googled it, and found a great answer on stack overflow

Basically, it takes advantage of python’s class access philosophy. Unlike java, which has a strict access policy, in python, all attributes and methods of a class are mutable. So it is possible to write code like this:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
return "ook ook eee eee eee!"

SomeClass.speak = speak

This could be particularly useful for unittesting, which is also mentioned in the stackoverflow answer

For instance, consider a class that has a method get_data. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don’t want to depend on the external data source – so you dynamically replace the get_datamethod with a stub that returns some fixed data.

Join 165 other subscribers

archives

  • 2024 (10)
  • 2023 (8)
  • 2022 (15)
  • 2021 (19)
  • 2020 (1)
  • 2019 (1)
  • 2018 (2)
  • 2017 (1)
  • 2016 (2)
  • 2015 (5)
  • 2014 (5)
  • 2013 (2)
  • 2011 (7)
  • 2010 (10)
  • 2009 (50)
  • 2008 (28)
  • 2007 (31)
  • 2006 (8)

Category