liveBook · Manning

Docstring

As explained in Get Programming: Learn to code with Python

A string associated with a code component that documents its inputs, behavior, and outputs.

A docstring is a multiline string that documents a code component’s inputs, behavior, and outputs. In Python, it appears inside a function between triple quotes and helps readers understand the function without studying every implementation detail. section 21.3 section 20.2

Documenting an attendance function

def take_attendance(classroom, who_is_here): """ classroom, tuple of strings who_is_here, tuple of strings Prints the names of students who are present Returns a string, "finished taking attendance" """ Read the docstring from top to bottom: it identifies each input and type, describes the task, and states the returned value. A reader can understand the function’s contract before examining its loop and condition. section 21.1 section 21.3

def take_attendance(classroom, who_is_here):
    """
    classroom, tuple of strings
    who_is_here, tuple of strings
    Prints the names of all kids in class who are also in who_is_here
    Returns a string, "finished taking attendance"
    """

Inspect the compact function specification for a complete example of parameter names, types, behavior, and return information. section 21.3

Use this checklist when writing a docstring:

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains docstring structure and purpose with a worked function example, without descending into documentation tools or advanced formats.
Examples
Uses an attendance function and a remote-control black-box analogy to show documented inputs, behavior, and outputs.
What it assumes
Assumes basic function definitions and introduces docstrings as a way to make function abstraction understandable.
What you can do after
Build it from scratch by writing a Python function specification with parameter types, behavior, and return information.
How it connects
Connects docstrings to functions, abstraction, parameters, return values, and black-box design.

Also explained in

Compare how 6 books explain docstring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.