Represent Missing Values with Unions
Core idea
A union A | B accepts either type according to the static contract (Python 3.10+). T | None, also written Optional[T], models a missing value. Narrow the union with an explicit is None check before using a value as T. Optional describes a type, not whether the caller may omit the argument.
def display(count: int | None) -> str: if count is None: return 'unknown' return str(count)print(display(None), display(0))Zero is a valid count and is not missing.
Default is a separate choice
def label(value: str | None = None) -> str: return 'unset' if value is None else valueprint(label())print(repr(label('')))The default allows omission; an empty string remains a value.
Common mistake
Do not replace an explicit None check with if not value when zero or empty text is valid. An annotation alone does not supply a default.
Practice
Write a formatter for int | None that preserves negative and zero values and gives a distinct missing label.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Union and optional types
Check your understanding of union and optional types.
What is printed?
def f(x: int | None) -> int: return 7 if x is None else xprint(f(0))What is printed?
def f(x: str | None = None) -> str: return 'N' if x is None else xprint(f())What is Optional[int] equivalent to?
Does a parameter annotation T | None let callers omit it?