Skip to course content
Free course

Python Foundations / Module 5 / Docstrings and Basic Type Hints

Module 5 lesson

Docstrings and Basic Type Hints

Unit ID: M05-U04 Estimated active time: 22-30 minutes

State what the function promises

def clean_status(raw_status: str) -> str:
    """Return status text with outside spaces removed and lowercase letters."""
    return raw_status.strip().lower()

The docstring explains the behaviour. The annotations suggest that the input and output are strings.

Hints are not automatic validation

Python normally allows this call to begin even with a type hint:

clean_status(42)

It then fails because an integer has no .strip() method. Type hints help readers, editors, and checking tools; they do not automatically enforce runtime types.

Write a useful docstring

A concise beginner docstring should state:

  • the result or action;
  • important assumptions; and
  • any intentional side effect.

Avoid repeating the function name without adding meaning.

Weak:

"""Clean status."""

Stronger:

"""Return status text after trimming outside spaces and converting to lowercase."""

Inspect documentation

help(clean_status)
print(clean_status.__doc__)

This connects your own functions with the documentation habits learned in Module 1.

Collection hints at a basic level

def total_hours(hours: list[int]) -> int:
    """Return the total of integer hour values."""
    return sum(hours)

This syntax requires a modern Python version. The course runtime will be pinned before publication.

Practice

Add a docstring and type hints to build_module_label(module_number, title, status="planned"). Then use help() and compare the displayed signature with the definition.

Takeaway

Docstrings explain the contract; type hints communicate intended types. Neither replaces input validation or executable tests. Next, we will learn to read object, attribute, and method syntax common in Python libraries.