liveBook · Manning

Docstring

As explained in Learn AI-Assisted Python Programming, Second Edition

A string literal placed in a program construct to document that construct and make its documentation available to programming tools.

A docstring is a string placed immediately after a Python function header to describe the function’s behavior. It names what parameters mean and what the function returns, helping both people and Copilot produce the intended function body. section 3.1.1 section 3.8

Write a useful docstring by making the function’s task explicit:

  • Describe each parameter, including its role or expected kind of value. section 7.7.1
  • State whether the function returns a value, and identify that result. section 7.7.1
  • Keep the task small and well defined; a description longer than a few sentences may signal that the function should be split. section 3.6.1
  • Add example calls and expected results when the docstring will also support testing. section 6.6.3

Prompting Copilot with a docstring

def larger(num1, num2): """ num1 and num2 are two numbers. Return the larger of the two numbers. """ if num1 > num2: return num1 else: return num2 The programmer chooses the function name and parameters, writes the docstring, and lets Copilot generate the body. A clear header and description reduce ambiguity compared with relying on comments alone. section 3.1.1

Executable examples

A docstring can contain doctest examples such as >>> tot_pass_yds_player('test_file.csv', 'Aaron Rodgers') followed by 800. Running the function with these cases provides evidence that its behavior matches the specification. section 6.6.3

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains placement, triple quotes, parameter descriptions, return statements, and doctest examples without discussing Python internals.
Examples
Demonstrates larger, create_word_list, and tot_pass_yds_player functions, including executable doctest cases.
What it assumes
Assumes basic Python function headers and parameters while teaching function behavior, return values, and testing through examples.
What you can do after
Build Python functions from a chosen header and docstring, then test documented behavior with doctest examples.
How it connects
Connects docstrings with functions, parameters, return values, Copilot, prompt engineering, unit testing, and problem decomposition.

Also explained in

Compare how 6 books explain docstring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.