title: Monkey patching a class in another module in Python
body: <p>I'm working with a module written by someone else. I'd like to monkey patch the <code>__init__</code> method of a class defined in the module. The examples I have found showing how to do this have all assumed I'd be calling the class myself (e.g. <a href="https://stackoverflow.com/questions/3765222/monkey-patch-python-class">Monkey-patch Python class</a>). However, this is not the case. In my case the class is initalised within a function in another module. See the (greatly simplified) example below:</p>
  <p><strong>thirdpartymodule_a.py</strong></p>
  <pre><code>class SomeClass(object):
      def __init__(self):
          self.a = 42
      def show(self):
          print self.a
  </code></pre>
  <p><strong>thirdpartymodule_b.py</strong></p>
  <pre><code>import thirdpartymodule_a
  def dosomething():
      sc = thirdpartymodule_a.SomeClass()
      sc.show()
  </code></pre>
  <p><strong>mymodule.py</strong></p>
  <pre><code>import thirdpartymodule_b
  thirdpartymodule_b.dosomething()
  </code></pre>
  <p>Is there any way to modify the <code>__init__</code> method of <code>SomeClass</code> so that when <code>dosomething</code> is called from mymodule.py it, for example, prints 43 instead of 42? Ideally I'd be able to wrap the existing method.</p>
  <p>I can't change the thirdpartymodule*.py files, as other scripts depend on the existing functionality. I'd rather not have to create my own copy of the module, as the change I need to make is very simple.</p>
  <p><strong>Edit 2013-10-24</strong></p>
  <p>I overlooked a small but important detail in the example above. <code>SomeClass</code> is imported by <code>thirdpartymodule_b</code> like this: <code>from thirdpartymodule_a import SomeClass</code>.</p>
  <p>To do the patch suggested by F.J I need to replace the copy in <code>thirdpartymodule_b</code>, rather than <code>thirdpartymodule_a</code>. e.g. <code>thirdpartymodule_b.SomeClass.__init__ = new_init</code>.</p>