I\'m working with a module written by someone else. I\'d like to monkey patch the __init__
method of a class defined in the module. The examples I have found sh
One only slightly-less-hacky version uses global variables as parameters:
sentinel = False
class SomeClass(object):
def __init__(self):
global sentinel
if sentinel:
else:
# Original code
self.a = 42
def show(self):
print self.a
when sentinel is false, it acts exactly as before. When it's true, then you get your new behaviour. In your code, you would do:
import thirdpartymodule_b
thirdpartymodule_b.sentinel = True
thirdpartymodule.dosomething()
thirdpartymodule_b.sentinel = False
Of course, it is fairly trivial to make this a proper fix without impacting existing code. But you have to change the other module slightly:
import thirdpartymodule_a
def dosomething(sentinel = False):
sc = thirdpartymodule_a.SomeClass(sentinel)
sc.show()
and pass to init:
class SomeClass(object):
def __init__(self, sentinel=False):
if sentinel:
else:
# Original code
self.a = 42
def show(self):
print self.a
Existing code will continue to work - they will call it with no arguments, which will keep the default false value, which will keep the old behaviour. But your code now has a way to tell the whole stack on down that new behaviour is available.