Functions & Reusable Code · Lesson 69

Docstrings

A docstring is a string literal placed as the first statement of a module, function, class or method to document its public purpose and interface.

ConceptWorked examplePracticeKnowledge check
Textbook walkthrough

Docstrings

A docstring is a string literal placed as the first statement of a module, function, class or method to document its public purpose and interface. Python stores it in the object’s __doc__ attribute, and help() can display it. A useful function docstring explains what the function does, important inputs, returned value and exceptional conditions without duplicating the implementation line by line.

Learning goal: explain why Docstrings behaves this way, apply it to a small example, and verify the result independently. Begin by being able to justify this first step: Place the docstring immediately after def/class or at the top of a module.

Deeper walkthrough

Read Docstrings as a mechanism, not a recipe

Treat this as a sequence of observable decisions rather than one opaque command. Stage 1: Place the docstring immediately after def/class or at the top of a module. Stage 2: Start with a concise purpose statement. Stage 3: Document parameters/returns when their meaning is not obvious from the signature. Final checkpoint: Keep the docstring correct as the interface changes.

Mechanism

Follow the transformation

Place the docstring immediately after def/class or at the top of a module.

Start with a concise purpose statement.

Document parameters/returns when their meaning is not obvious from the signature.

Evidence

Know what would convince you

  • Trace a tiny input by hand and compare the runtime result.
  • Inspect type, value/shape and any mutation/side effect explicitly.
Useful distinctionInput: Objects/values supplied to the operation.
Click a stage to inspect what happens, what changes, and what should be checked before moving on.
Stage 1

Place the docstring immediately after def/class…

Place the docstring immediately after def/class or at the top of a module. For Docstrings, identify the exact state before this stage, the operation or rule applied here, and the observable state afterwards so the mechanism remains inspectable.

State focus: identify exactly what changed at this stage and what observable evidence confirms that change.
How it works

Trace the mechanism step by step

  1. Place the docstring immediately after def/class or at the top of a module.
  2. Start with a concise purpose statement.
  3. Document parameters/returns when their meaning is not obvious from the signature.
  4. Mention important units, side effects or raised exceptions.
  5. Keep the docstring correct as the interface changes.
Worked demonstration

Function documentation

# Step 1 — Define the reusable `percentage` function; its indented body describes what happens for each call.
def percentage(part, whole):
    # Step 2 — Execute this statement and inspect how it changes the current value, object or program state.
    """Return part as a percentage of whole; whole must be positive."""
    # Step 3 — Evaluate this condition and execute the indented branch only when the condition is true.
    if whole <= 0:
        # Step 4 — Raise an explicit exception to signal that the required condition or input contract was violated.
        raise ValueError("whole must be positive")
    # Step 5 — Return the computed value to the caller so the result can be reused or tested.
    return 100 * part / whole

# Step 6 — Display the current value explicitly so the result/state can be inspected during execution.
print(percentage.__doc__)
Expected / illustrative result
The docstring is attached to the function object and can be surfaced by help(percentage).
Interpret the result.

For Docstrings, trace the specific input through the mechanism above and independently verify one returned value, state change or side effect.

Distinctions & related ideas

Place the concept correctly

InputObjects/values supplied to the operation.
StateNames or mutable objects that may change during execution.
OutputReturned value, side effect, file, plot or exception to inspect.
Use deliberately

When it is appropriate

Use Docstrings when it answers a defined question in Functions & Reusable Code and its inputs/assumptions match the current data or program state.

Boundary conditions

When to stop or reconsider

Reconsider Docstrings when the required information is unavailable, the operation would violate a validation/data boundary, or a simpler operation answers the question more transparently.

Common mistakes

Failure modes to recognise

  • Running the operation on the wrong object/type or in the wrong environment.
  • Inferring correctness from “no exception” without checking the produced value/state.
  • Hiding a boundary case instead of making its behaviour explicit.
Verification

How to check the result

  • Trace a tiny input by hand and compare the runtime result.
  • Inspect type, value/shape and any mutation/side effect explicitly.
  • Run an edge or invalid case and confirm the exception/behaviour is deliberate.
Hands-on practice

Demonstrate understanding

Try this:

Construct a tiny example of Docstrings. First place the docstring immediately after def/class or at the top of a module. Then start with a concise purpose statement. Predict the result before execution and explain one boundary or failure case.

Use the smallest values that expose the language rule. Write the expected value and type first, then compare the actual state/output with that prediction.
Knowledge check

Check reasoning, not memorisation

Which approach best demonstrates understanding of Docstrings?

Quick reference

Remember the logic

Step 1Place the docstring immediately after def/class or at the top of a module.
Step 2Start with a concise purpose statement.
Step 3Document parameters/returns when their meaning is not obvious from the signature.
Step 4Mention important units, side effects or raised exceptions.
Lesson summary

What to remember

  • A docstring is a string literal placed as the first statement of a module, function, class or method to document its public purpose and interface. Python stores it in the object’s __doc__ attribute, and help() can display it. A useful function docstring explains what the function does, important inputs, returned value and exceptional conditions without duplicating the implementation line by line.
  • Place the docstring immediately after def/class or at the top of a module.
  • Running the operation on the wrong object/type or in the wrong environment.
  • Trace a tiny input by hand and compare the runtime result.