Guido van Rossum wrote: > On Tue, Jan 4, 2011 at 1:50 PM, Steven D'Aprano <steve at pearwood.info> 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? Because there was no source code -- I was experimenting in the interactive interpreter. I could have just re-created the function by using the readline history, but it was just easier to redefine len. Oh... it's just occurred to me that you were asking for use-cases for assigning to builtins.len directly, rather than just to len. No, I've never done that -- sorry for the noise. >> 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. Ha, well, that's the sort of thing that gives monkey-patching a bad name, surely? Is there a use-case for globally replacing builtins for all modules, everywhere? I suppose that's what you're asking. The only example I can think of might be the use of mocks for testing purposes, but even there I'd prefer to inject the mock into the module I was testing: mymodule.len = mylen But I haven't done much work with mocks, so I'm just guessing. -- Steven
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4