The limits of monkey patching in Python

November 25, 2012

One of the things I find interesting is the question of why monkey-patching is a common thing in the Ruby world but not in the Python world. Certainly a significant part of this is cultural (Python culture is very much against monkey patching, Ruby culture seems to be completely accepting of it), but it's hard for me to believe that that's the whole story. People do things to solve problems and I don't believe that Python is magically without the problems that cause people to monkey-patch Ruby. I've recently come up with not so much a theory as an observation on this.

One of the things that people do with Ruby monkey-patching is adding convenience methods to core Ruby classes, things like strings and arrays. You can't do this in Python, because Python monkey-patching has a fundamental limit: you can't monkey-patch anything written in C. Well, you can't monkey-patch it unless it went out of its way to let you, and most modules written in C don't.

There's two aspects of this. To start with, a fair number of the interesting Python classes and modules are written in C, including (of course) all of the fundamental types. These are all de facto sealed from modification and given that Python's culture is against monkey-patching it's unlikely that a proposal to change that would be accepted (to put it one way). This means that you simply can't do a fair amount of the monkey patching that happens in Ruby.

More generally, that C-level things can't be monkey patched makes it at least somewhat dangerous to patch anything that might plausibly be turned into a C module even if it isn't one right now. This is probably especially likely to happen to popular data structures (any number of which have made journeys from Python to C). If such a transition does happen, your monkey patching will immediately fail and you'll have to find another way.

(I don't know if this really acts as a disincentive, though, because I'm not sure that people who might monkey patch such things are aware of this issue.)

Written on 25 November 2012.
« Simple markup as a style guide and limiter
More thoughts on why Python doesn't see much monkey-patching »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Sun Nov 25 03:38:21 2012
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.