[Tutor] Regarding Exceptions

Steven D'Aprano steve at pearwood.info
Sat Feb 22 02:50:20 CET 2014


On Fri, Feb 21, 2014 at 01:27:55PM -0500, eryksun wrote:
> On Fri, Feb 21, 2014 at 12:48 PM, wesley chun <wescpy at gmail.com> wrote:
> > in reality, built-ins are part of a magical module called __builtins__
> > that's "automagically" imported for you so that you never have to do it
> > yourself. check this out:
> >
> >>>> __builtins__.Exception
> > <type 'exceptions.Exception'>
> >
> > you can also find out what all the other built-ins are using dir():
> >>>> dir(__builtins__)
> > ['ArithmeticError', 'AssertionError', 'AttributeError',...]
> 
> In __main__, __builtins__ is the __builtin__ module (no "s"):
> 
>     >>> __builtins__
>     <module '__builtin__' (built-in)>

Built-ins is confusing.

__builtins__ with an S is a special, implementation-specific hack for 
CPython only, it is *not* part of the language and you should not rely 
on it. Never use __builtins__, it is considered for internal use only.

In Python 2, the built-in objects live inside a module called 
__builtin__ (with no S). Like all modules, you have to import it before 
you can access the module. Unlike other modules, it's automatically 
used to look up names, even if you haven't imported it. So when you 
refer to a name like "foo", or "len", or "Exception", Python searches 
the local variables, the global variables, and the built-ins, before 
raising NameError if it is not found at all.

The difference between private __builtins__ and public __builtin__ is 
confusing and subtle and easy to get wrong, so in Python 3 the built-in 
module was renamed to "builtins".

# Don't do this, this is bad.
__builtins__.len

# Instead, do this in Python 2.
import __builtin__
__builtin__.len

# Or in Python 3.
import builtins
builtins.len



The history of __builtins__ with an S is quite old. It's used for 
performance reasons, and originally it was supposed to be used for 
sandboxing Python, but that turned out to not work. So although it still 
exists even in Python 3, it's a performance hack for the CPython 
interpreter, and does not exist in Jython, IronPython or other 
interpreters.


-- 
Steven


More information about the Tutor mailing list