androidengineers.Book a session

Python 05 · Functions and modules

Type hints, optional values, and data contracts

articleSelf-paced

Learn the concept

Type hints describe expected inputs and outputs for readers and static analysis tools. Python does not automatically enforce annotations at runtime. Continue validating values at boundaries such as JSON parsing or user input.

An optional value represents a meaningful absence. Use str | None when a value may be missing and handle that branch explicitly. Avoid pretending that an empty string and no value are equivalent unless your domain says so.

Typed containers describe their elements, such as list[str]. Small typed functions make transformations easier to follow. Static analysis can find inconsistent uses before execution, while tests and runtime checks address actual behavior. These methods complement each other rather than replace one another.

Run and inspect

from __future__ import annotations

def label(document_id: str, title: str | None) -> str:
    if title is None:
        return f"{document_id}: untitled"
    return f"{document_id}: {title}"

assert label("d1", None) == "d1: untitled"
assert label("d1", "") == "d1: "

Your exercise

Annotate a parsing function that can return a missing title. Create tests for None, empty text, and a valid title. Explain which invalid values annotations alone would not stop.

Check your understanding

The missing-value behavior is explicit and you do not claim that an annotation validates incoming JSON.

YOUR LEARNING JOURNEY

0 of 42 available lessons completed

Progress saved in this browser. No account needed.
Type hints, optional values, and data contracts | Python for AI Engineering | Android Engineers