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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With