Python 3.6.1: How to dynamically print a docstring?

Question:

While reading some Python training books, I was tinkering a little bit with objects, like printing docstrings for common objects and attributes.

Consider the list of strings returned by:

dir(str)

I am trying to iterate over the above in order to dynamically print the docstrings of the attributes stored in the dir list with the following loop:

for item in dir(str):
    print(item.__doc__)

This returns the dir output for the str object and not for its attribute though, which is not what I’m looking for. How can I dynamically print instead the docstring for all the attributes that populate the list produced by the dir method?

EDIT: this is NOT a duplicate of this other question.
Using the word “enumerate” is very misleading, at least to me, so I would say that question is improperly titled in fact I spent a lot of time looking for a solution and no search query ever returned that.

Asked By: alfx

||

Answers:

You can use getattr(obj, attr) to get the named attribute from the object.

for item in dir(str):
    print(getattr(str, item).__doc__)
Answered By: khelwood

Instead of using dir, which just gives you the names of attributes, use vars – this gives you a dict of names to the actual method objects.

for name, method in vars(str).items():
    print(name, method.__doc__)
Answered By: Daniel Roseman