Skip to content Skip to sidebar Skip to footer

How To Add My Own "help" Information To A Python Function/class?

I know I can use 'help()' to see existing help information from packages. But after I wrote my own function/class, how can I enable 'help' to see help document? I know the first li

Solution 1:

help() is entirely based on __doc__ attributes (and introspection of function arguments), so make sure your module, your classes and your functions all have a docstring.

A docstring is not a comment, it is a bare string literal right at the top:

"""This is a module docstring, shown when you use help() on a module"""classFoo:
    """Help for the class Foo"""defbar(self):
        """Help for the bar method of Foo classes"""defspam(f):
    """Help for the spam function"""

For example, the popular third-party requests module has a docstring:

>>> import requests
>>> requests.__doc__
'\nRequests HTTP library\n~~~~~~~~~~~~~~~~~~~~~\n\nRequests is an HTTP library, written in Python, for human beings. Basic GET\nusage:\n\n   >>> import requests\n   >>> r = requests.get(\'https://www.python.org\')\n   >>> r.status_code\n   200\n   >>> \'Python is a programming language\' in r.content\n   True\n\n... or POST:\n\n   >>> payload = dict(key1=\'value1\', key2=\'value2\')\n   >>> r = requests.post(\'http://httpbin.org/post\', data=payload)\n   >>> print(r.text)\n   {\n     ...\n     "form": {\n       "key2": "value2",\n       "key1": "value1"\n     },\n     ...\n   }\n\nThe other HTTP methods are supported - see `requests.api`. Full documentation\nis at <http://python-requests.org>.\n\n:copyright: (c) 2016 by Kenneth Reitz.\n:license: Apache 2.0, see LICENSE for more details.\n'

which is rendered by help() directly, together with the module contents (and recursively, the content docstrings):

>>> help('requests')
Help on package requests:

NAME
    requests

DESCRIPTION
    Requests HTTP library
    ~~~~~~~~~~~~~~~~~~~~~

    Requests is an HTTP library, written in Python, for human beings. Basic GET
    usage:

       >>> import requests
       >>> r = requests.get('https://www.python.org')
       >>> r.status_code
       200
[...]

Solution 2:

You could use argparse: https://docs.python.org/2/howto/argparse.html. It allows you to create a --help parameter that you can customize as well as add argument descriptions.

Example:

parser = argparse.ArgumentParser(description = "Write your help documentation here...")
parser.add_argument('config.txt', nargs='?', help='Write about your positional arguments here')
args = parser.parse_args()

So when someone runs your program with --help it will output:

$python yourProgram.py --help
usage: yourProgram.py [-h] [config.txt]

Write your help documentation here...

positional arguments:
config.txt  Write about your positional arguments here

optional arguments:
-h, --help  show this help message and exit

Post a Comment for "How To Add My Own "help" Information To A Python Function/class?"