Why does `__builtins__` not contain itself?

69 Views Asked by At

The following code seems like a good way to get an overview of the builtin objects in Python.

dunder = []  # 8

lower_fun = []  # 41
lower_type = []  # 26
lower_sitebuiltins = []  # 6

upper_exception = []  # 50
upper_warning = []  # 11
upper_other = []  # 10


for name, obj in vars(__builtins__).items():
    first_char = name[0]
    if first_char == '_':
        dunder.append(name)
    else:
        if first_char.islower():
            t = str(type(obj))
            if t == "<class 'builtin_function_or_method'>":
                lower_fun.append(name)
            elif t == "<class 'type'>":
                lower_type.append(name)
            elif '_sitebuiltins' in t:
                lower_sitebuiltins.append(name)
            else:
                assert False  # does not happen
        else:
            if 'Error' in name or 'Exception' in name:
                upper_exception.append(name)
            elif 'Warning' in name:
                upper_warning.append(name)
            else:
                upper_other.append(name)

I would have expected __builtins__ to appear in dunder. But it is not there.

dunder == [
    '__name__', '__doc__', '__package__', '__loader__',
    '__spec__', '__build_class__', '__import__', '__debug__'
]

Apparently I do not understand, what "built in" means.
So what are the 152 entries of vars(__builtins__)?
And what (like __builtins__) is missing?


Edit: builtins and sys are also not in these lists.

The 152 entries came from running this code from a Python file.
In a console dir(__builtins__) looks completely different, and has only 41 entries.
vars(__builtins__) causes a TypeError in the console.

Initially the code used dir(__builtins__). Following the advice in a comment, it was rewritten using vars(__builtins__). The result is essentially the same, but the lists have a different order.

0

There are 0 best solutions below