28.3. __builtin__ — 内置对象

此模块提供对 Python 所有内置标识符的直接访问;例如, __builtin__.open 是完整名称对于内置函数 open() 。见 内置函数 and 内置常量 文档编制。

大多数应用程序通常不会明确访问此模块,但在提供同名内置值对象的模块 (其中还需要内置名称) 中会很有用。例如,当模块想要实现 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 实现细节: Most modules have the name __builtins__ (note the 's' ) made available as part of their globals. The value of __builtins__ is normally either this module or the value of this modules’s __dict__ 属性。由于这是实现细节,因此 Python 的替代实现可能不会使用它。

上一话题

28.2. sysconfig — 提供对 Python 配置信息的访问

下一话题

28.4. future_builtins — Python 3 内置

本页