Write a documented function in Python and read its docstring back at runtime.
A docstring is a string literal that you place as the first statement inside a function, a class, or a module. It becomes the __doc__ attribute of the object, so it is still available while the program is running instead of being thrown away by the interpreter.
import inspect
def area(width, height):
"""Return the area of a rectangle.
Args:
width: the width in metres.
height: the height in metres.
Returns:
The area in square metres.
"""
return width * height
print(area(3, 4)) # 12
print(area.__doc__)
print(area.__name__)
print(inspect.getdoc(area))The printed docstring is the whole text of the literal, including the indentation of the continuation lines, so the raw __doc__ output looks ragged. That is exactly why inspect.getdoc exists. It cleans the indentation up and returns a properly formatted block, and that is what the documentation tools use.
There are three points to make in an interview. First, the docstring must be the very first statement, because a docstring placed after any other statement is just an unused string expression and the __doc__ attribute will be None. Second, it is not a comment, because it survives into the compiled bytecode and it can be read by help(), by doctest, and by the documentation generators. Third, the triple-quoted form is only needed because docstrings usually run over several lines. A one-line docstring can use ordinary quotes.
The convention for a multi-line docstring is that the closing triple quote goes on a line of its own, which is why the indented Args and Returns sections above line up the way that they do.