Search code examples
pythonoopmethodsmetaprogrammingdocstring

Is there a way to print a short version of the docstring for all members of a Python object?


In Python dir() returns the list of names in the current local scope. __doc__ returns the complete docstring of an object.

How can I list all names in the current local scope and print the first line of each item's docstring ?

To elaborate: for import numpy as np I would like to get a list of short descriptions of all names returned by dir(np) e.g. print(np.nonzero.__doc__.split('.', 1)[0]).

How can I do this ?


Solution

  • def print_members(obj):
        for key in dir(obj):
            value = getattr(obj, key)
            doc = (value.__doc__ or '').split('.', 1)[0]
            print('MEMBER: %s\nDOCSTRING: %s\n\n' % (key, doc))