8

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?

0

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.