Recently Guido offered up a couple of interesting recipes for cleaner monkey_patch implementations via decorators and metaclasses.
I think monkeypatching can be a very useful tool in the same way that a jackhammer or a shotgun can be useful tools. When you need them, nothing else can do the job as well. Of course, you can always smash the cement by hand with heavy iron rods — as is sometimes done in India, where labor is often cheaper than tools… Feel free to make your own analogy to using static languages and the trend towards code generation, rather than having the right tool for the job. But don’t expect me to do it, I’m trying to take the high road today ;)
Anyway, some of the responses have been along the lines of “I like my monkeypatching to look ugly, because it deters people from doing it.” And while I have a lot of respect for some of the folks saying this, I’ve never been a fan of this kind of “syntactic vinegar” argument. It seems to me that it’s better to make complex things seem easy than it is to make simple things seem hard. And it’s kind of paternalistic, and not consistent with the “we’re all consenting adults here” philosophy behind Python. Sure people could do stupid things with these tools, but I think it’s a bad idea to spend your time trying to stop hypothetical bad programmers from doing stupid things.
In other words, we shouldn’t make jackhammers more ugly and complicated just because you would smash your living room wall to pieces if you tried to hang a picture with one. ;)
And I think these patterns are useful. The first decorator syntax is particularly valuable for stubbing interface points out for testing purposes. Hey, a it’s a “mock framework” in 5 lines of code. The second looks like a nice thing to have around for testing purposes too. I’m sure there are uses beyond testing, but I know that’s where I’m likely to start applying these monkeypatching helpers.