Sub topic 6
Narrowing Types with Checks
This chapter assumes you can annotate parameters and returns, write X | None unions, and run mypy or pyright on a file. Here you will learn how a checker turns a wide type such as str | None into a narrower one such as str, based on the checks in your code.
What narrowing is
A declared type says what a name could hold. Narrowing is the checker's reasoning about what the name must hold at one specific line, given the checks that came before it.
def shout(name: str | None) -> str:
if name is None:
return "nobody"
return name.upper()
print(shout(None))
print(shout("ada"))At the top of shout, name is str | None. Inside the if block it is None. After the early return, the only remaining possibility is str, so name.upper() is accepted. Without the check, the checker reports that None has no attribute upper.
Both mypy and pyright support reveal_type(expr). The checker prints the narrowed type at that line. At runtime the call does not exist in mypy and fails with NameError, so remove it before running the file. Pyright accepts it only as a checker aid in the same way.
Checks the checkers understand
A checker narrows only on forms it recognizes. Common ones are listed below.
| Check | Narrows |
|---|---|
| `x is None`, `x is not None` | Removes or keeps `None` |
| `isinstance(x, T)` | Keeps `T` in the true branch, removes it in the false branch |
| `x == "a"` on a `Literal` type | Keeps the matching literal |
| `x in ("a", "b")` | Narrows to the listed literals in many cases |
| `callable(x)` | Keeps callable members of a union |
| `if x:` | Removes `None`, and removes values that are always falsy |
isinstance
def total(value: int | list[int]) -> int:
if isinstance(value, int):
return value
return sum(value)
print(total(5))
print(total([1, 2, 3]))In the true branch, value is int. After the return, the checker knows only list[int] remains, so sum(value) is valid. isinstance also accepts a tuple of classes, as in isinstance(value, (int, float)).
Use the plain class in isinstance, not a subscripted generic. isinstance(value, list[int]) raises TypeError at runtime, because the interpreter cannot inspect the elements. Write isinstance(value, list), and the checker narrows to list[int] using the declared type.
Truthiness
Testing if x: removes None, but it also removes every value that is falsy at runtime.
def describe(count: int | None) -> str:
if count:
return f"{count} items"
return "no count"
print(describe(0))The checker accepts this code. The call prints no count, although 0 is a valid count. Use if count is not None: when None is the only case you mean to exclude. Reserve plain truthiness tests for cases where an empty string, empty list, or zero should be treated like a missing value.
Narrowing by assignment and the walrus operator
Assigning a value narrows a name from that point on.
def clean(text: str | None) -> str:
if text is None:
text = ""
return text.strip()
print(repr(clean(None)))
print(repr(clean(" hi ")))After the if, both paths leave text as str. The assignment expression := combines a call and a check:
import re
def first_number(line: str) -> int | None:
if (match := re.search(r"\d+", line)) is not None:
return int(match.group())
return None
print(first_number("room 42"))re.search returns re.Match[str] | None. Inside the if, match is the Match type.
Exhaustiveness checking
Narrowing also works across several branches. If you test every member of a union or every Literal value, the checker knows nothing is left. You can ask it to prove that with assert_never, available from typing in Python 3.11 and later (typing_extensions for older versions).
from typing import Literal, assert_never
Shape = Literal["circle", "square"]
def area(kind: Shape, size: float) -> float:
if kind == "circle":
return 3.14159 * size * size
elif kind == "square":
return size * size
else:
assert_never(kind)
print(area("square", 3))In the final else, kind has been narrowed to Never, which is the type with no values, so the call is accepted. Suppose you later add "triangle" to Shape and forget a branch. In the final else, kind becomes Literal["triangle"], and the checker reports an error at the assert_never call. At runtime assert_never raises AssertionError if it is ever reached, so it also guards against bad data.
Writing your own narrowing function
Sometimes the check is too complex for the built-in forms. A user-defined type guard is a function whose return type tells the checker what a true result means.
from typing import TypeGuard
def is_str_list(values: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(v, str) for v in values)
data: list[object] = ["a", "b"]
if is_str_list(data):
print(", ".join(data))When the function returns True, the checker treats data as list[str]. The checker does not verify your function body. If the body is wrong, the narrowing is wrong, and nothing warns you.
TypeGuard narrows only the true branch. Python 3.13 added typing.TypeIs (also in typing_extensions), which narrows both branches like isinstance does. Prefer TypeIs when the narrowed type is a subtype of the input type.
When narrowing is lost
Narrowing lasts only while the checker can be sure the name has not changed. Keep these cases in mind:
- Reassigning the name replaces the narrowed type with the type of the new value.
- Narrowing of attributes such as
self.tokenorconfig.pathstays in effect until you assign to that attribute. Calling a method between the check and the use does not reset it, even though that method might change the attribute. The checkers accept this for convenience, so it is a gap in their checking. - Narrowing of a name inside a nested function or lambda depends on the checker and its version. If the outer name is reassigned after the nested function is defined, the narrowing generally does not carry in.
A reliable habit is to copy the value into a local variable and narrow that:
class Session:
def __init__(self) -> None:
self.token: str | None = None
def header(self) -> str:
token = self.token
if token is None:
raise RuntimeError("not logged in")
return f"Bearer {token}"
session = Session()
session.token = "abc"
print(session.header())The local token cannot be changed by other code, so the narrowing is trustworthy. Raising an exception in the None case also removes None from the remaining code, just as an early return does.
Narrowing versus cast
typing.cast(T, x) tells the checker to treat x as T. It does nothing at runtime and checks nothing. A real check such as isinstance is better, because it protects you at runtime too. Use cast only where you know something the checker cannot, and add a comment saying why.
Exercise
A function takes limit: int | None. The body starts with if not limit: return []. A caller passes 0 and expects up to zero results to be processed normally, but gets [] for a different reason than intended. What is the problem, and what check fixes it?
Show answer
not limit is true for both None and 0, so the checker accepts the code but the runtime treats a valid 0 like a missing value. Use if limit is None: to exclude only None, and handle 0 as an ordinary integer afterward.
Exercise
You have def label(level: Literal["low", "high"]) -> str with branches for "low" and "high". What do you add after the last branch so that a future "medium" value in the Literal produces a checker error, and what does the call do at runtime?
Show answer
Call assert_never(level) in a final else branch. The checker reports an error when level is not Never there, which happens once "medium" is added without a branch. At runtime the call raises AssertionError if the line is ever reached.