Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 871
Josh Reuben Avatar asked Aug 21 '17 12:08

Josh Reuben


People also ask

How do I print a docstring function?

If you need to print the docstring of the current module, use the __doc__ global variable, e.g. print(__doc__) . Copied! We used the __doc__ attribute to print the docstring of a file. The __doc__ attribute returns the module's or function's documentation string or None if there isn't a docstring.

What does __ doc __ mean in Python?

The __doc__ attribute Each Python object (functions, classes, variables,...) provides (if programmer has filled it) a short documentation which describes its features. You can access it with commands like print myobject.

How do you get a Python docstring?

Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function. An object's docstring is defined by including a string constant as the first statement in the object's definition.

Can we use one liner docstring?

Per convention, you use one-line docstrings if the function, module, class, or method is obvious enough to warrant a short explanation—but nothing more. You can enclose the one-liner docstring within single quotes, double quotes, or even triple quotes.


1 Answers

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))
like image 129
Danil Speransky Avatar answered Sep 24 '22 12:09

Danil Speransky