Explore Books related to Python. Click Here

Python: An Example of Bad Monkey Patching

Today one of my coworkers came and got me so that I could explain some weird Python code they'd found. It dealt with cmake, but since it was internal code, I won't be able to show it here. Instead, I wrote up something that has the same issues so you can see what I consider bad, or at the very least, very obtuse code:

class Config:
    def Run(self):
        print('Program Usage: blah blah blah')
        self.asset_tag = 'test'
        total = self.sub_total_a + self.sub_total_b

When I first saw this, I was struck by how it was using attributes that weren't initialized and I wondered how this could work. Then I realized they must be doing some kind of monkey patching. Monkey patching is where you write code to dynamically modify a class or module at run time. So I looked farther down the script and found some code that created an instance of the class and did something like this:

def test_config():
    cfg = Config()
    cfg.product = 'laptop'
    cfg.asset_tag = '12345ABCD'
    cfg.sub_total_a = 10.23
    cfg.sub_total_b = 112.63
if __name__ == '__main__':

So basically whenever you create an instance of the class, you need to patch it so that the attributes exist before you call the Run method.

While I think it's pretty cool that Python can do this sort of thing, it is extremely confusing to someone who is not familiar with Python, especially when the code was as poorly documented as this was. As you can see, there are no comments or docstrings, so it took a bit of digging to figure out what was going on. Fortunately, all the code was in the same file. Otherwise this could have gotten really tricky to figure out.

I personally thought this was a good example of bad coding. If I had written it, I would have created an __init__ method and initialized all those attributes there. Then there would have been no confusion about how the class worked. I am also a big believer in writing good docstrings and useful comments.

Anyway, I hope you found this interesting. I also thought my readers should be aware of some of the oddball pieces of code you'll see in the wild.

Copyright © 2022 Mouse Vs Python | Powered by Pythonlibrary