Python Get Docstring without going online

I want to capture a docstring in my command line application, but every time I call the built-in help () function, Python goes into interactive mode.

How to get docstring of an object and not have Python capture focus?

+5
source share
3 answers

Any docstring is available through the property .__doc__:

>>> print str.__doc__

In python 3 you will need a bracket to print:

>>> print(str.__doc__)
+7
source

dir( {insert class name here} ), , , . Task , cmd, docstring:

command_help = dict()

for key in dir( Task ):
    if key.startswith( 'cmd' ):
        command_help[ key ] = getattr( Task, key ).__doc__
+3

.__doc__- the best choice. However, you can use inspect.getdocto receive docstring. One of the benefits of using this is to remove indents from docstrings that have indents to line up with blocks of code.

Example:

In [21]: def foo():
   ....:     """
   ....:     This is the most useful docstring.
   ....:     """
   ....:     pass
   ....: 

In [22]: from inspect import getdoc

In [23]: print(getdoc(foo))
This is the most useful docstring.

In [24]: print(getdoc(str))
str(object='') -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
+1
source

All Articles