Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading