Built-in objects in Python (builtins)

PythonProgrammingServer Side Programming

The builtins module is automatically loaded every time Python interpreter starts, either as a top level execution environment or as interactive session. The Object class, which happens to be the base class for all Python objects, is defined in this module. All built-in data type classes such as numbers, string, list etc are defined in this module. The BaseException class, as well as all built-in exceptions, are also defined in it. Further, all built-in functions are also defined in the built-ins module.

Since this module is imported in the current session automatically, normally it is not imported explicitly. All the built-in functions used in the executable code are by default considered to be from built-ins module. For example

>>> len('hello')

is implicitly equivalent to

>>> import builtins
>>> builtins.len('hello')

However, explicit import of this module is required when there is also a user defined function of the same name as built-in function. Python interpreter gives higher precedence to user defined function. Hence, if the code contains both user defined as well as built-in function of the same name, the latter must be prefixed with built-ins module.

def len(string):
print ('local len() function')
print ('calling len() function in builtins module')
import builtins
l = builtins.len(string)
print ('length:',l)
string = "Hello World"


local len() function
calling len() function in builtins module
length: 11

Most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__attribute.

>>> import math
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': <module 'math' (built-in)>}
Published on 27-Dec-2018 13:10:45