Ravindra BagaleCourses & study guides मराठी Track your progress

Python Functions Tutorial: def, return, Arguments and lambda with Examples

P7.6 How to Write a Docstring for a Python Function

In short: A docstring is a text in triple quotes as the first line of the function. help(func) shows it.

Why. A teammate (or you, later) needs to know what the function expects and returns without reading every line.

What. A docstring is a text in triple quotes as the first line of the function. help(func) shows it.

How.

Document a function

  1. Right after the def line, open """.
  2. Write one line: what it does.
  3. Mention inputs and the return value.
  4. Close with """.

Worked example A — A documented cleaner.

Step 1 — What we do. A function used by a healthcare data team.

Step 2 — Type and run this code.

def clean_name(text):
    """Return a patient name with no outer spaces and Title Case."""
    return text.strip().title()

print(clean_name("  maria lopez "))
print(clean_name.__doc__)

Step 3 — Output you should see.

Maria Lopez
Return a patient name with no outer spaces and Title Case.

Step 4 — What it means. The docstring is stored with the function. In Jupyter, press Shift+Tab inside the brackets to see it.

Ravindra Bagale's Tip

One clear sentence in a docstring is better than none. Write it while the idea is fresh.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.