"Don't rebind built-in names*" - it confuses readers

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jun 12 21:08:25 EDT 2013


On Thu, 13 Jun 2013 10:08:14 +1000, Chris Angelico wrote:

>>>> int="five"
>>>> [__builtins__.int(i) for i in ["1","2","3"]]

Don't use __builtins__, it's an implementation detail.

In Python 2.x, there is __builtins__ with an "s" in the global namespace 
if you are running CPython, but not necessarily other implementations. 
There is __builtin__ with no "s" which is defined by the language, but 
you have to import it first.

In Python 3.x, you just import builtins with an "s" and no underscores, 
no matter what implementation you use.


> It's shadowed, not overwritten.

But even if you override it, you can get it back:


py> import builtins
py> builtins.int = "five"  # My monkey has a patch.
py> int("42")  # Oh-oh, trouble ahead
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
py> builtins.int = type(5)
py> int("42")
42


It may not be quite so simple to recover from *all* such monkey-patches, 
but you can always exit Python, edit your code, and start it up again. 
It's not like you've patched the actual compiler.



-- 
Steven



More information about the Python-list mailing list