-1

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.'
MikeiLL
  • 6,282
  • 5
  • 37
  • 68
  • 1
    Does anything stop you from doing something like `for k,v in __builtins__.__dict__.items():print(k, inspect.getdoc(v))`? – Mous Aug 30 '23 at 21:08
  • 1
    If the key in this dictionary is the name of a module, function or something else, the value is the actual object. – Michael Butscher Aug 30 '23 at 21:08
  • "But you know that at that point "b" is just a string of the name of the module." - did you try using it as a key in `__builtins__.__dict__` (which you already know to be a dictionary)? – Karl Knechtel Aug 30 '23 at 22:03

1 Answers1

2

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:
    print(k, v)
Mous
  • 953
  • 3
  • 14