1

I'm fairly new to python. I know docstrings are used for documentation and I can use help() to call them. My question is, when I write my own function in a .py file with documentation, for example:

file - foo.py

def foo():
    """
    foo documentation
    """
    some code here

How can I print out the "foo documentation" from the terminal or interactive session? Thanks.

kaifi
  • 126
  • 1
  • 8

2 Answers2

1

function_name.__doc__ is used to get the docstring of a function in python

As an example below is the docstring of commonly used range function of python

range.__doc__
'range(stop) -> list of integers\nrange(start, stop[, step]) -> list of integers\n\nReturn a list containing an arithmetic progression of integers.\nrange(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\nWhen step is given, it specifies the increment (or decrement).\nFor example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\nThese are exactly the valid indices for a list of 4 elements.'
Shrey
  • 1,242
  • 1
  • 13
  • 27
0

In a REPL session it is possible to use help rather than accessing .__doc__ directly:

>>> def foo():
...     """
...     foo documentation
...     """

>>> help(foo)
Help on function foo:
foo()
    foo documentation

>>>

.__doc__ only returns the docstring as a raw string:

>>> foo.__doc__
'\n    foo documentation\n    '

>>>
DeepSpace
  • 78,697
  • 11
  • 109
  • 154