Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Strings & text processingJuniorCommonPractical

How do triple-quoted strings relate to docstrings, and how are docstrings retrieved at runtime?

Answer

A triple-quoted string (`"""..."""` or `'''...'''`) lets a string literal span multiple lines and include embedded quote characters without escaping. A docstring, by definition, is any string literal expression that appears as the very first statement inside a module, class, function or method body — a single-quoted one-liner in that position is technically a docstring too; triple quotes are just the normal, conventional style because they read well for multi-line documentation. Python automatically stores whichever string literal fills that role on that object's `__doc__` attribute, and tools like `help()`, IDEs and documentation generators read `__doc__` to display usage information without needing separate documentation files.

Strong answer includes

  • triple quotes allow multi-line literals with embedded quotes
  • a docstring is defined by syntactic position — the first statement in a block — not by triple-quoting itself
  • stored automatically on __doc__, read by help() and doc tools

Practical example

Python example
def add(a, b):
    """Return the sum of a and b."""
    return a + b

makes `add.__doc__` equal to `"Return the sum of a and b."` , retrievable at runtime via

Python example
help(add)

.

#strings#docstrings

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics