On Tue, Jan 4, 2011 at 1:50 PM, Steven D'Aprano email@example.com wrote:
I've been known to monkey-patch builtins in the interactive interpreter and in test code. One example that comes to mind is that I had some over-complicated recursive while loop (!), and I wanted to work out the Big Oh behaviour so I knew exactly how horrible it was. Working it out from first principles was too hard, so I cheated: I knew each iteration called len() exactly once, so I monkey-patched len() to count how many times it was called. Problem solved.
But why couldn't you edit the source code?
I also have a statistics package that has its own version of sum, and I rely on calls to sum() from within the package picking up my version rather than the builtin one.
As long as you have a definition or import of sum at the top of (or really anywhere in) the module, that will still work. It's only if you were to do things like
import builtins builtins.len = ...
(whether inside your package or elsewhere) that things would stop working with the proposed optimization.
-- --Guido van Rossum (python.org/~guido)