Absence and Contracts

Lesson 50 of 54 · Python Foundations

Sometimes a result can be absent. str | None means a string or the special value None; this union syntax requires Python 3.10 or newer. None is different from an empty string: one denotes absence, the other is still a string.

def first_label(labels: list[str]) -> str | None:
    if labels:
        return labels[0]
    return None

for labels in [["map", "key"], []]:
    result = first_label(labels)
    if result is None:
        print("no label")
    else:
        print(result.upper())
MAP
no label

The explicit is None branch separates absence from a usable string before calling a string method. A function that performs an action and returns no meaningful value is commonly annotated -> None.

A contract also helps expose mismatched implementations. The function below promises a pair with a text unit followed by a numeric reading. Returning (reading, unit) instead reverses the positions: a type checker can flag that mismatch.

def measurement(reading: float) -> tuple[str, float]:
    unit = "C"
    return (unit, reading)

print(measurement(18.5))
('C', 18.5)

A checker can point out a reversed pair, but it cannot prove that the unit or reading is correct. Annotations complement, rather than replace, execution and tests.