28.3. __builtin__ —内置对象

该模块可直接访问 Python 的所有“内置”标识符;例如,__builtin__.open是内置函数open()的全名。有关文档,请参见Built-in FunctionsBuilt-in Constants

通常,大多数应用程序都不会显式访问此模块,但是在为对象提供与内置值同名的对象的模块中,该模块很有用,但其中还需要该名称的内置物。例如,在要实现包装内置open()open()函数的模块中,可以直接使用此模块:

import __builtin__

def open(path):
    f = __builtin__.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '''Wrapper around a file that converts output to upper-case.'''

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

    # ...

CPython 实现细节: 大多数模块的名称__builtins__(请注意's')作为其全局变量的一部分可用。 __builtins__的值通常是此模块或此模块的dict属性的值。由于这是一个实现细节,因此 Python 的其他实现可能不会使用它。