List built-in objects with dir(__builtins__) in Python
Python has many built-in objects, such as functions and constants. This article explains how to access a list of these built-in objects.
Check built-in objects in the official documentation
The official documentation provides detailed explanations of these built-in objects.
If you want to know what built-in objects are available, it is best to read the official documentation.
- Built-in Functions — Python 3.12.1 documentation
- Built-in Types — Python 3.12.1 documentation
- Built-in Constants — Python 3.12.1 documentation
- Built-in Exceptions — Python 3.12.1 documentation
The builtins
module and __builtins__
The standard library includes the builtins
module to access built-in objects like built-in functions.
For example, you can call the built-in len()
function as builtins.len()
. These two are the same object.
import builtins
print(len('abc'))
# 3
print(builtins.len('abc'))
# 3
print(len)
# <built-in function len>
print(builtins.len)
# <built-in function len>
print(builtins.len is len)
# True
Typically, there's no need to explicitly use the builtins
module. However, it is useful when creating a custom function that wraps a built-in function while retaining the same name.
In many implementations of Python, you can use __builtins__
to access the builtins
module without importing it.
print(__builtins__.len('abc'))
# 3
print(__builtins__.len is len)
# True
print(__builtins__ is builtins)
# True
List built-in objects with dir()
The built-in dir()
function returns a list of attributes for the specified object.
By passing the builtins
module or __builtins__
to dir()
, you can obtain a list of built-in object names.
Here, pprint
is used to make the output easier to read.
Note that in environments where __builtins__
is different from the builtins
module, you should import the builtins
module and use dir(builtins)
instead of dir(__builtins__)
.
import pprint
print(type(dir(__builtins__)))
# <class 'list'>
print(len(dir(__builtins__)))
# 153
pprint.pprint(dir(__builtins__), compact=True)
# ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
# 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
# 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
# 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
# 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
# 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning',
# 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError',
# 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError',
# 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError',
# 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
# 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning',
# 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError',
# 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration',
# 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
# 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError',
# 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
# 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError',
# 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__',
# '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__',
# 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray',
# 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright',
# 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval',
# 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr',
# 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',
# 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map',
# 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow',
# 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',
# 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',
# 'vars', 'zip']
The results vary depending on the environment. The output in the above example is from running it in Jupyter Notebook (IPython), so it includes values like '__IPYTHON__'
and 'get_ipython'
.
The list returned by dir()
comprises only the names as strings, without indicating whether each name represents a function, a constant, or another type of object.
print(dir(__builtins__)[0])
# ArithmeticError
print(type(dir(__builtins__)[0]))
# <class 'str'>
For example, using list comprehensions and string methods, you can filter names to include only those in lowercase (excluding those starting with '_'
) or those ending with 'Error'
or 'Warning'
.
pprint.pprint([s for s in dir(__builtins__) if s.islower() and not s.startswith('_')], compact=True)
# ['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray',
# 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright',
# 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval',
# 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr',
# 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',
# 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map',
# 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow',
# 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',
# 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',
# 'vars', 'zip']
pprint.pprint([s for s in dir(__builtins__) if s.endswith('Error')], compact=True)
# ['ArithmeticError', 'AssertionError', 'AttributeError', 'BlockingIOError',
# 'BrokenPipeError', 'BufferError', 'ChildProcessError',
# 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError',
# 'ConnectionResetError', 'EOFError', 'EnvironmentError', 'FileExistsError',
# 'FileNotFoundError', 'FloatingPointError', 'IOError', 'ImportError',
# 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError',
# 'KeyError', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError',
# 'NotADirectoryError', 'NotImplementedError', 'OSError', 'OverflowError',
# 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError',
# 'RuntimeError', 'SyntaxError', 'SystemError', 'TabError', 'TimeoutError',
# 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
# 'UnicodeError', 'UnicodeTranslateError', 'ValueError', 'ZeroDivisionError']
pprint.pprint([s for s in dir(__builtins__) if s.endswith('Warning')], compact=True)
# ['BytesWarning', 'DeprecationWarning', 'FutureWarning', 'ImportWarning',
# 'PendingDeprecationWarning', 'ResourceWarning', 'RuntimeWarning',
# 'SyntaxWarning', 'UnicodeWarning', 'UserWarning', 'Warning']
As mentioned above, if you simply want to know what built-in objects are available in Python, it is best to check the official documentation. However, if you want to check whether a particular string is used as a built-in object name, dir(__builtins__)
is handy.
You can check as follows:
print('len' in dir(__builtins__))
# True
Using the same name as a built-in object for a variable name should be avoided as it can overwrite the original.