Sub topic 7
Narrowing Literal values and checking exhaustiveness
This chapter assumes you can read basic type hints and know that a static checker such as mypy or pyright analyzes annotations without running your program. You should also know how to write Literal["a", "b"] and give it a name with an alias. Here you will see how a checker narrows a Literal type after a comparison, and how to make it report a missing case.
What narrowing means
A parameter annotated Literal["pending", "active", "closed"] can hold three values. After the code tests one of them, the checker knows more about the variable inside each branch. This is called narrowing: the checker replaces the declared type with a smaller one wherever the test guarantees it.
from typing import Literal
Status = Literal["pending", "active", "closed"]
def is_open(status: Status) -> bool:
if status == "closed":
# Here status is Literal["closed"]
return False
# Here status is Literal["pending", "active"]
return True
print(is_open("active"))Checkers narrow in both directions. The if branch keeps only the matching member, and the code after it keeps the remaining members. Nothing about this changes how the program runs. The checker is reasoning about the annotations only.
Forms of test that narrow
Not every condition narrows. The table lists the common forms. Support varies by checker and version, so confirm important cases with your own tool.
| Test | Effect on a `Literal` variable |
|---|---|
| `x == "a"` | Keeps `"a"` in the true branch, removes it in the false branch |
| `x != "a"` | The reverse of `==` |
| `x in ("a", "b")` | Keeps `"a"` and `"b"` in the true branch (pyright; mypy support is narrower) |
| `match x:` with `case "a":` | Keeps `"a"` inside that case and removes it from later cases |
| `x is "a"` | Do not use. Identity checks on strings are unreliable and trigger warnings |
Narrowing lasts only while the checker can be sure the variable has not changed. If you reassign the variable, the narrowed type is discarded and the declared type applies again.
Checking exhaustiveness with assert_never
Narrowing becomes useful when you chain tests that cover every member. After the last test, the checker has removed all the possibilities, so the variable has type Never, the type with no values. You can turn that fact into an error by passing the variable to assert_never, which only accepts Never.
from typing import Literal, assert_never
Status = Literal["pending", "active", "closed"]
def label(status: Status) -> str:
if status == "pending":
return "Waiting"
elif status == "active":
return "In progress"
elif status == "closed":
return "Done"
else:
assert_never(status)
print(label("active"))assert_never is in typing from Python 3.11. On older versions, import it from typing_extensions.
The function type-checks because, in the else branch, status has been narrowed to Never. Now suppose someone adds a fourth value:
Status = Literal["pending", "active", "closed", "archived"]The else branch now sees Literal["archived"]. The checker reports that this argument cannot be assigned to a parameter of type Never, and it points at the assert_never line. The error appears in every function that branches on Status and forgot the new value. This is the main reason to prefer a Literal alias over bare strings.
What happens at runtime
At runtime, assert_never raises an AssertionError if it is ever called. That only happens when a value outside the declared type reaches the function, for example a string read from a file. So it works in two ways. A checker uses it for a compile-time guarantee, and the running program gets a loud failure instead of silently returning None.
from typing import Literal, assert_never
Status = Literal["pending", "active", "closed"]
def label(status: Status) -> str:
if status == "pending":
return "Waiting"
elif status == "active":
return "In progress"
elif status == "closed":
return "Done"
else:
assert_never(status)
try:
label("archived") # type: ignore[arg-type]
except AssertionError as error:
print("caught:", error)Exhaustiveness with match
A match statement does the same job and reads more clearly when there are many members. The wildcard case is where you put assert_never.
from typing import Literal, assert_never
Status = Literal["pending", "active", "closed"]
def label(status: Status) -> str:
match status:
case "pending":
return "Waiting"
case "active":
return "In progress"
case "closed":
return "Done"
case _:
assert_never(status)
print(label("closed"))Checkers treat a match over a Literal as exhaustive when every member has a case. With a return type declared, mypy and pyright can report a missing case even without assert_never, because the function could fall off the end and return None. Keeping the explicit assert_never gives you a clearer message and a runtime guard.
Getting from str to a Literal
Data from files, network requests and command lines arrives as str. A str is not a Literal, and an == test on a plain str does not turn it into one. You need a function the checker trusts to do the conversion. TypeGuard declares that a function returns True only when its argument has the given type.
from typing import Literal, TypeGuard, get_args
Mode = Literal["r", "w", "a"]
MODES: tuple[Mode, ...] = get_args(Mode)
def is_mode(value: str) -> TypeGuard[Mode]:
return value in MODES
def parse_mode(raw: str) -> Mode:
if is_mode(raw):
return raw
raise ValueError(f"unknown mode: {raw!r}")
print(parse_mode("w"))Two points about this pattern:
get_args(Mode)reads the allowed values from the alias, so the list of values is written once. Adding"x"toModeupdatesMODESautomatically.- The checker trusts your
TypeGuardfunction without verifying it. If the body returnedTruefor every string, the checker would still accept the narrowing.TypeGuardonly narrows the true branch. Python 3.13 addsTypeIs, which also narrows the false branch, andtyping_extensionsprovides it for earlier versions.
Keeping data tables in sync
A dictionary keyed by a Literal alias looks exhaustive, but the checker does not require every key to be present.
from typing import Literal, get_args
Status = Literal["pending", "active", "closed"]
LABELS: dict[Status, str] = {
"pending": "Waiting",
"active": "In progress",
}
missing = set(get_args(Status)) - set(LABELS)
print("missing labels:", sorted(missing))This dictionary is accepted even though "closed" is absent, and a lookup would raise KeyError. Checkers do not enforce completeness for a dict. A cheap fix is a test that compares set(get_args(Status)) with the dictionary keys, as the last two lines do. If you want the checker itself to enforce completeness, use the if/match form with assert_never, or a TypedDict with one required key per member.
Common problems
- A variable infers as
str. Writingmode = "r"at module level and then using it inside a function gives a checker astr, which is rejected where aModeis expected. Annotate it (mode: Mode = "r") or writemode: Final = "r", which keeps the literal type. - A new member breaks no checks. If the code uses
if/elifwithout a finalassert_never, adding a member is silent. The function returnsNonefor the new value. Always end the chain withassert_never. - Reassignment cancels narrowing. After
status = something_else(), the checker applies the declared type again. - Mixed value kinds.
Literalalso accepts integers, booleans, bytes, enum members andNone. Narrowing works for all of them, and amatchover an enum is checked the same way.
Exercise
The function below type-checks today. Later, someone changes the alias to Literal["low", "medium", "high", "urgent"]. What does the checker report, and why? What single change makes the function handle the new value? from typing import Literal, assertnever Priority = Literal["low", "medium", "high"] def weight(priority: Priority) -> int: if priority == "low": return 1 elif priority == "medium": return 5 elif priority == "high": return 10 else: assertnever(priority)
Show answer
After the three tests, priority is narrowed to Literal["urgent"] in the else branch instead of Never. The checker reports that this argument is not assignable to the Never parameter of assert_never, and the error points at that line. Adding a branch such as elif priority == "urgent": return 20 removes the leftover member, the narrowed type becomes Never again, and the error disappears.
Exercise
A function receives a raw string from a command-line argument and must pass it to code that expects Literal["r", "w", "a"]. Why does checking raw == "r" in a chain of branches not give you a Mode, and what should you write instead?
Show answer
A plain str is not narrowed to a Literal by an equality test, so the checker still sees str. Write a TypeGuard function, for example def ismode(value: str) -> TypeGuard[Mode] that returns value in getargs(Mode), and call it in an if. Inside the true branch the checker treats the value as Mode. The false branch should raise an error for an unknown mode.