[Python-3000] __builtin__ and __builtins__

Ka-Ping Yee python at zesty.ca
Mon Mar 12 01:37:51 CET 2007


For a long time __builtin__ and __builtins__ have mystified me.
Usually I end up guessing -- in any given namespace, one of the
two will exist, and it will either be a module or a dictionary --
but I never committed to memory which name or type to expect.

A little investigation reveals:

    In module __main__:
        __builtins__ is a reference to module __builtin__.
        __builtin__ only exists if you import it.

    In any other module:
        __builtins__ is a reference to module __builtin__'s __dict__.
        __builtin__ only exists if you import it.

In order of increasing boldness, here are some possible fixes:

    1.  Make __builtins__ always refer to a dict.  I think there's
        quite a strong argument for this -- in general, you should
        be able to take the same code and run it as a script or a
        module with similar behaviour.

    2.  Rename __builtins__ so it isn't so easily mistaken for __builtin__.
        I haven't thought of any awesome names to propose.

    3.  Unify the roles of the names __builtins__ and __builtin__ --
        having both is too confusing.

        a.  Instead of putting __builtins__ into every module namespace,
            import __builtin__ into every module namespace.

        b.  Do the last resort for name lookups in
            __builtin__.__dict__ instead of __builtins__.

        c.  To make this no slower than it is today, make each module
            cache a pointer to its __builtin__.__dict__ and update
            that pointer when __builtin__ is reassigned.

Going all the way to #3 would be the cleanest, I think.  Maybe
there are other solutions for unifying the two, as well -- any ideas?


-- ?!ng


More information about the Python-3000 mailing list