Sub topic 5
Unions and values that may be None
This chapter assumes you can write basic annotations (name: str, -> int), use built-in generics like list[int], and have run a static checker such as mypy or pyright. Type hints are not enforced at runtime, so everything below is reported by the checker, not by Python.
What a union means
A union type says a value may be one of several types. Write it with |:
def describe(value: int | str) -> str:
return f"got {value}"
print(describe(7))
print(describe("seven"))Union syntax with | works at runtime in annotations from Python 3.10. On older versions, use typing.Union[int, str] or add from __future__ import annotations.
Optional values
The most common union is a type plus None. str | None means "a string, or nothing". It fits functions that may not find a result.
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(1, {1: "Ada"})
if name is not None:
print(name.upper())dict.get returns None for a missing key, so the return type must admit None. The caller now has to deal with that case. Calling name.upper() before the check is an error, because None has no upper method.
What the checker reports
Remove the if and run the checker on the same code:
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(1, {1: "Ada"})
print(name.upper())mypy reports Item "None" of "str | None" has no attribute "upper". The program would crash at runtime only when the user is missing. The checker finds that case before the code runs.
Handling the None case
The is not None test narrows the type. Inside the if block the checker treats name as str. Other forms also work:
def shout(name: str | None) -> str:
if name is None:
return "nobody"
return name.upper()
def label(name: str | None) -> str:
return name or "anonymous"The early return in shout narrows name to str for the rest of the function. The or form in label is shorter, but it also replaces an empty string. Use is None when "" is a valid value.
Common errors
| Mistake | Result | Column |
|---|---|---|
| Calling a method on `X | None` without a check | Checker error: `None` has no such attribute |
| Declaring `-> str` but returning `None` on some path | Checker error: incompatible return value | |
| Using `if name:` when `0` or `""` is valid | Valid values are treated like `None` | |
| Writing `x: int = None` | Checker error unless the type is `int | None` |
Unions with more members work the same way. A checker only allows operations that every member supports, until you narrow the type.
Exercise
A function parse_port(text: str) -> int | None returns None when the text is not a number. Write one line of calling code that adds 1 to the result safely, and say why parse_port("80") + 1 is rejected by the checker.
Show answer
port = parse_port("80") followed by if port is not None: print(port + 1) works. The direct addition is rejected because the result may be None, and None + 1 would raise a TypeError at runtime. The is not None check narrows the type to int.