Why no warnings when re-assigning builtin names?

Ethan Furman ethan at stoneleaf.us
Wed Aug 17 14:13:30 EDT 2011


Seebs wrote:
> On 2011-08-17, Ethan Furman <ethan at stoneleaf.us> wrote:
>> Seebs wrote:
>>> On 2011-08-17, Steven D'Aprano wrote:
>>>> Ah, well you see the thing is, this is Python. As soon as you call any
>>>> function you don't control, you no longer know what your environment is
>>>> with any certainty. For all you know, the harmless-looking function is
>>>> monkey-patching builtins like there's no tomorrow. Speaking broadly,
>>>> perhaps too broadly, we're incredibly proud of the ability to modify nearly
>>>> everything at runtime.
> 
>>>> Fortunately, while we are proud of having that ability, actually *using* it
>>>> is considered a mortal sin. We're not Ruby developers -- if you actually
>>>> monkey-patch something, especially built-ins, you can expect to be taken
>>>> outside and slapped around with a fish if you get caught.
> 
>>> Here's what I don't get.
> 
>>> If it's such a bad thing, *why is it allowed*?  Why are you proud of the
>>> ability to do something that you are never socially-allowed to do?
> 
>> Monkey-patching built-ins would be something along the lines of
> 
>>      import sys
>>      sys.modules['__builtin__'].str = my_super_string
> 
>> and is what stands you in jeopardy of being fish-slapped.  ;)
> 
>> Merely shadowing a built-in, or stdlib, or whatever, isn't monkey-patching.
> 
> Oh, I know.  I was just noticing that Steven's post is specifically talking
> about how Python users are proud of having the ability to monkey-patch.
> 
> If monkey-patching like that is a mortal sin, leads to fish-slapping, and
> so on..
> 
> Why is it possible?  Why not just reject such things as invalid code?

Well, the mortal sin part is a bit of an exaggeration -- it's more like 
you'd better have a really darn good reason to do it.  And it is 
absolutely one of my favorite parts about Python.  If I want to inject a 
custom Path class into builtins so it's readily available, and then 
change os.listdir to return it instead of normal strings, I can.  If my 
application is truly case-insensitive, I can make my own istr class and 
monkey-patch builtins so it's what is used.  Can this blow-up in my 
face?  Certainly.  But I would rather have the option open to me instead 
of being told "No, I'm sorry, you can't do that because I (developers in 
question) didn't imagine a good use case for it".

Part of the fun of Python is experimentation.  And how much fun is it to 
be told over and over, "No, you can't do that"?

As an example of something that could easily have been outlawed, but 
wasn't, check out http://stackoverflow.com/questions/7068340

~Ethan~



More information about the Python-list mailing list