Loop through module and run inspect.getdoc() on each method

I can print a list of all the builtins:

for i, b in __builtins__.__dict__:
    print(i, b)

__name__
__doc__
__package__
__loader__
__spec__
__build_class__
__import__
abs
all
any
ascii
...

Then import inspect and inspect.getdoc(<some_module>).

First thought was:

for b in __builtins__.__dict__:
    print(b, inspect.getdoc(b))

But you know that at that point "b" is just a string of the name of the module.

Tried: dir(__builtins__), which also seems to be a list of strings.

Using list wont work:

list(__builtins__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not iterable

Obviously, I can just read the docs online, but am wondering if there is a way to do what I’m trying to do within Python… rather how it can be done.

Ultimately, it would be really cool to have a little generator that can output them one by one:

mybuiltins.next()
Method: reversed
Doc: 'Return a reverse iterator over the values of the given sequence.'

>Solution :

This should work, using dict.items:


builtins = {k: inspect.getdoc(v) for k, v in __builtins__.__dict__.items()}

Here’s some example usage:

# Get a specific builtin
builtins['reversed'] # 'Return a reverse iterator over the values of the given sequence.'
getattr(__builtins__, 'reversed') # <class 'reversed'>
# List all the builtin names, and their doc, as in your example
for k, v in builtins.items():
    print(k, v)

Leave a Reply