Get Python's help() function stored as string just like console



Python’s help function lets you see the help message written for you by the developer. It is particularly useful in IDLE / shell to inspect modules and explore.

Here is a sample shell demo

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

Now if we want to store that text in a string, if we try x = help(print), we get not a string, but a surprise:

>>> x = help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

>>> x
>>> x
>>> type(x)
<class 'NoneType'>
>>>

Ugh. How the to get the doctring as a string?

In Enters Pydoc

Pydoc is used to generate documentations

Here is the snippet to store the docstring as a variable

from pydoc import render_doc
doctring = render_doc(print)

Simple isn’t it?

instead of print, add any module.

Written by

Abdur-Rahmaan Janhangeer

Chef

Python author of 9+ years having worked for Python companies around the world

Suggested Posts

The Zen Of Python: A Most In Depth Article

Note: I wrote a quite complete article on the Zen but for some reason it went down in seo history. I...

Read article

Python Generators: The In-depth Article You've Always Wanted

Table of contents Why were Python generators introduced? How do Python Generators differ from norma...

Read article

Python: Making Imports Callable

I wanted to do import module module() I thought this did not exist in Python but Chris Angelico, a...

Read article
Free Flask Course