[Tutor] lists of lists: more Chutes & Ladders!

Steven D'Aprano steve at pearwood.info
Wed Jan 1 04:53:06 CET 2014


On Tue, Dec 31, 2013 at 10:00:32PM -0500, eryksun wrote:
> On Tue, Dec 31, 2013 at 4:27 AM, spir <denis.spir at gmail.com> wrote:
> > In addition, "iter" is also the name of a builtin function, like "print".
> 
> While iter is a built-in function, it would be clearer if you
> referenced the __builtins__ namespace. 

Don't use __builtins__!

Firstly, it's an implementation detail only in CPython, not part of the 
language. So it doesn't exist in Jython or IronPython:

Jython 2.5.1+ (Release_2_5_1, Aug 4 2010, 07:18:19)
[OpenJDK Server VM (Sun Microsystems Inc.)] on java1.6.0_27
Type "help", "copyright", "credits" or "license" for more information.
>>> import __builtins__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named __builtins__

__builtins__ with-an-s is a crappy hack that has never worked correctly 
and has caused more confusion than help:

https://mail.python.org/pipermail/python-3000/2007-March/006170.html

"Restricted mode" in CPython has never worked correctly, __builtins__ 
has always been an implementation-specific detail, and you should never 
use it. The one you actually want is "__builtin__" (no "s") in Python 2, 
or "builtins" (no underscores) in Python 3.


> Built-in objects are linked
> into the interpreter, either statically or from a shared library (.so,
> .pyd). But the __builtins__ namespace can and does include names for
> non-built-in objects (e.g. help and exit).

Only when running interactively, and only when site.py runs. If you 
remove or disable site.py, the help and exit functions don't get added.

Actually, there's nothing special about site.py, anyone or anything 
could monkey-patch builtins. Don't do this:

py> spam  # Does spam variable exist?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
py> import builtins
py> builtins.spam = "spam spam spam"
py> del builtins
py> spam
'spam spam spam'



> The important point in this
> context is that iter is in the builtins module, not that it's a
> built-in function. There are lots of built-in objects that aren't in
> builtins.


I'm afraid I've lost the context, and don't understand why this is 
important. It's true that not all built-in objects are in builtins, and 
not all objects in builtins are built-in, but other than for pedantic 
correctness, why does this matter?


-- 
Steven


More information about the Tutor mailing list