Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print your function's documentation python [duplicate]

I have been searching for an answer for a lot of time now. Let's say I wrote a function in python and I made a brief documentation of what this function is doing. Is there any way to print the function's documentation from within main? Or from the function itself?

like image 277
Nahman Khayet Avatar asked Dec 14 '15 21:12

Nahman Khayet


1 Answers

You can either use help() or print the __doc__. help() prints a more verbose description of an object while __doc__ holds only the documentation string you have defined with triple quotes """ """ in the beginning of your function.

For example, using __doc__ explicitly on the sum built-in function:

print(sum.__doc__)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.

Additionally, since Python first compiles an object and during execution evaluates it you can call __doc__ within the function with no problems:

def foo():
    """sample doc"""
    print(foo.__doc__)

foo()  # prints sample doc

and remember, besides functions, modules and classes have a __doc__ attribute holding their documentation.

Alternatively, using help() for sum:

help(sum)

Will print:

Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

gives a bit more information, including the docstring.

like image 53
Dimitris Fasarakis Hilliard Avatar answered Sep 30 '22 18:09

Dimitris Fasarakis Hilliard