Monkey Patches, friend or foe?


MetaProgramming (which means writing programs for the sake of modifying running programs), is commonplace in languages such as Python and Ruby. It often becomes evident that the work you need to do could easily be accomplished by introducing additional functionality at runtime. Monkey Patching, a concept within MetaProgramming, is a very hot topic in the world of dynamic languages.

For example, let’s pretend we’re developing an information sensitive application written in Django and deployed on Google’s AppEngine. You want to insert a message into the log anytime something is deleted from the database, and audit this list daily. This problem quickly becomes easy to solve because you have the ability to modify any class in memory, regardless if it’s a third party and closed platform or not. Thanks to monkey patching, the code to do this is really simple.


from google.appengine.ext import db
from norex.utils import monkey_patch
class Model(db.Model):
     __metaclass__ = monkey_patch
     def __delete__(key):
        import logging
        logging.info("HOLY SMOKES SOMETHING WAS DELETED!!!")
        return super(Model,self).__delete(key)

From this simple example, we can see that Monkey Patching is serious business. Some developers hail it as being a fantastic language feature; an equal amount of others cower in fear when you start modifying core classes at runtime and good reason. When monkey patches go un-documented, or get lost in the source, you can drive yourself insane trying to find out the reason for when you’re asking for some information, no matter what, it comes out upside down. It’s probably because someone did this:


class Query(old.Query):
    __metaclass__ = monkey_patch
    def all(self, **kwargs):
        return Query.did_you_see_the_pool()
        #screw this return super(Query, self).all(), I need my queries flipped upside down!

Small changes like these occasionally go un-documented, which means you’re S.O.L until you do a ‘rgrep monkey_patch “*.py”‘ and notice that in some obscure library Joe decided he needed to flip his queries (whatever that means). Firstly, Joe’s a bum. He should know better than to do this sort of thing without providing proper documentation; this is precisely why above programmers are worried. Modifying code at runtime requires a lot of responsibility. I’m a firm believer that just because a language feature gives you the ability to shoot yourself in the foot, it doesn’t mean you need your hand held throughout the process of coding. If done correctly, and responsibly I think it’s a perfectly legitimate way to solve or diagnose a problem quickly and cleanly.

What do you think?

, , , ,

  1. No comments yet.
(will not be published)
  1. No trackbacks yet.