[Tutor] Regarding Exceptions

eryksun eryksun at gmail.com
Fri Feb 21 19:27:55 CET 2014


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)>

I have no idea why. I guess someone thinks this is convenient? In
every other pure-Python (not built-in) module, it defaults to the dict
of the __builtin__ module:

    >>> import __builtin__, os
    >>> os.__builtins__ is vars(__builtin__)
    True

That's the default when a module is executed. However, it's possible
to exec and eval code with a custom __builtins__:

    >>> ns = {'__builtins__': {'msg': 'spam'}}
    >>> exec 'print msg' in ns
    spam
    >>> eval('msg', ns)
    'spam'

Just don't be deluded into thinking it's possible to sandbox Python like this.


More information about the Tutor mailing list