builtins — 內建物件


該模組提供對 Python 所有“內建”識別符號的直接訪問;例如,builtins.open 是內建函式 open() 的完整名稱。

大多數應用程式通常不會顯式訪問此模組,但它在提供與內建值同名的物件的模組中非常有用,但其中也需要該名稱的內建值。例如,在想要實現一個包裝內建 open()open() 函式的模組中,可以直接使用此模組。

import builtins

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

class UpperCaser:
    '''Wrapper around a file that converts output to uppercase.'''

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

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

    # ...

作為實現細節,大多數模組都有一個名為 __builtins__ 的名稱作為其全域性變數的一部分。 __builtins__ 的值通常是這個模組或這個模組的 __dict__ 屬性的值。由於這是一個實現細節,Python 的替代實現可能不會使用它。