Sub topic 7
Narrowing Literal values and checking exhaustiveness
This chapter assumes you can write Literal annotations and run a checker such as mypy or pyright. It also assumes you know if/elif chains. Python 3.11+ is needed for assert_never from typing. On older versions, import it from typing_extensions.
What narrowing means
A parameter typed as Literal["pending", "shipped", "delivered"] can hold one of three values. After a comparison, the checker knows more about it. Inside if status == "pending":, the type is Literal["pending"]. In the code that follows, the checker removes that case from the remaining options. This is called narrowing.
Exhaustiveness with assert_never
Narrowing lets the checker prove that every case is handled. When you reach the final else, nothing should be left. The type of the variable there is Never, which has no values. assert_never accepts only an argument of type Never, so the checker reports an error if any value can still reach that line.
from typing import Literal, assert_never
Status = Literal["pending", "shipped", "delivered"]
def label(status: Status) -> str:
if status == "pending":
return "Waiting to ship"
elif status == "shipped":
return "On the way"
elif status == "delivered":
return "Arrived"
else:
assert_never(status)
print(label("shipped"))This code passes the check. Now suppose you delete the delivered branch, or add a fourth value such as "returned" to Status. At the else line, status is no longer Never. The checker reports an error, for example that Literal['delivered'] cannot be assigned to parameter of type Never. The error points at the function that needs updating, so you do not have to search for it.
Using match
A match statement narrows the same way. Each case with a literal value removes that value, and the wildcard case _ is the place for assert_never.
from typing import Literal, assert_never
Status = Literal["pending", "shipped", "delivered"]
def is_finished(status: Status) -> bool:
match status:
case "pending" | "shipped":
return False
case "delivered":
return True
case _:
assert_never(status)
print(is_finished("pending"))What happens at runtime
assert_never is a normal function. If it is ever called, it raises AssertionError. That is useful as a backstop. The checker only sees the annotations. If a caller passes "returned" through an untyped path, such as JSON parsing, the checker could not catch it. The else branch then fails loudly instead of returning None silently.
Common mistakes
- Narrowing a plain
str. If the parameter isstr, comparing it with"pending"does not produce aLiteraltype. The annotation must beLiteral[...]or an alias for it. - Skipping a value. Missing a
Literalmember in theifchain is the intended error. Fix it by adding a branch, not by silencing the checker. - Narrowing through a mutable variable. If you reassign the variable between the test and its use, the checker may discard what it learned.
- Relying on other forms. Comparisons with
==andmatchare widely supported. Narrowing throughinorisvaries between checkers and versions, so check your tool's documentation.
Exercise
You have Color = Literal["red", "green", "blue"] and a function that handles "red" and "green" with if/elif, then ends with else: assert_never(color). What does the checker report, and what is the type of color in the else branch?
Show answer
The checker reports an error because color is Literal["blue"] in the else branch, not Never, and assert_never only accepts Never. The fix is to add an elif color == "blue": branch. After that, color is Never in the else branch and the error disappears.