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. Narrowing is how a static checker works out that a wide type is really a narrower one at a given line.
What narrowing does
A union such as str | None allows two kinds of value. Calling .upper() on it is an error, because None has no such method. A check in your code tells the checker which branch you are in. Inside that branch, the checker treats the variable as the narrower type.
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()) # name is str hereInside the if block the checker sees str. Outside it, name is still str | None.
Checks that narrow
| Check | Narrows to |
|---|---|
| `x is None` / `x is not None` | removes or keeps `None` |
| `isinstance(x, int)` | `int` in the true branch |
| `if x:` (truthiness) | removes `None`, and for some types `0` or `""` |
| `x == "r"` on a `Literal` | the matching literal value |
| `callable(x)` | callable types only |
Prefer is None over a truthiness test when 0 or an empty string is a valid value. if not count: would treat 0 as missing.
Narrowing with isinstance
isinstance works well on unions of unrelated types.
def describe(value: int | str | list[int]) -> str:
if isinstance(value, int):
return f"number {value + 1}"
if isinstance(value, str):
return f"text {value.upper()}"
return f"list of {len(value)} items"After the two early returns, the checker knows only list[int] remains, so len(value) is accepted. Each early return removes a type from the union for the code below it.
Common errors
- Narrowing is lost after reassignment or a function call. If you assign a new value to the variable, the checker starts again from the declared type. Attributes such as
self.namecan also lose their narrowing after a call, because the call might change them. - Checking in one place and using in another. Narrowing applies only to the code the check controls. A check in one function does not narrow a variable in another.
- Using
assertfor narrowing.assert name is not Nonedoes narrow the type. It is also removed when Python runs with-O, so do not rely on it for real validation.
Exercise
Exercise
A function takes value: int | None. It runs if not value: return "missing", and the caller passes 0. What does the function return, and which check would handle 0 correctly?
Show answer
It returns "missing", because 0 is falsy. Use if value is None: return "missing" so that 0 is treated as a real value.
Exercise
In def f(x: int | str) -> str:, the body is if isinstance(x, int): return "n". What type does the checker give x on the next line?
Show answer
str. The isinstance branch returned, so only str remains.