Sub topic 6
Narrowing types with isinstance, None checks, and conditions
This chapter assumes you can read basic annotations, know union types such as int | str, and can run mypy or Pyright on a file. Examples use Python 3.10 or newer. assert_never needs Python 3.11, or typing_extensions on older versions.
What narrowing is
A union type says a value could be one of several types. Most operations only work on some of them. Narrowing is the checker's ability to shrink a union to fewer members inside a code region, based on a test the code performs. The checker reads your if statements and tracks what each branch proves.
Narrowing is a static analysis only. The test still runs at runtime. The checker just learns from it.
def describe(value: int | str | list[int]) -> str:
reveal_type(value) # int | str | list[int]
if isinstance(value, int):
reveal_type(value) # int
return f"int {value + 1}"
elif isinstance(value, str):
reveal_type(value) # str
return value.upper()
reveal_type(value) # list[int]
return str(sum(value))After the int branch returns, the checker removes int from the union. After the str branch returns, it removes str. Only list[int] remains for the last line. Each type check removes a member from what is left.
Forms of narrowing both checkers understand
| Test | True branch | False branch | Column |
|---|---|---|---|
| `x is None` | `None` | the union without `None` | |
| `x is not None` | the union without `None` | `None` | |
| `isinstance(x, C)` | `C` (or the matching members) | the union without `C` | |
| `isinstance(x, (A, B))` | `A \ | B` | the union without `A` and `B` |
| `x == "a"` with `Literal` types | `Literal["a"]` | the other literals | |
| `callable(x)` | the callable members | the non-callable members | |
| `if x:` | removes `None` and falsy-only types | may still include falsy values | |
| `"key" in x` with TypedDict unions | members that may have the key | the rest |
None checks
Use is None and is not None for optional values. They are exact: only the None object matches.
def shout(name: str | None) -> str:
if name is None:
return ""
return name.upper()Returning early is the most readable pattern. Everything after the if runs only when name is a str, so the rest of the function needs no extra nesting. The same works with raise, continue, and break.
isinstance with classes and tuples
isinstance narrows to the class you test. If the declared type is a base class, the checker narrows to the subclass in the true branch.
class Animal: ...
class Dog(Animal):
def bark(self) -> str:
return "woof"
def speak(pet: Animal) -> str:
if isinstance(pet, Dog):
return pet.bark()
return "..."Passing a tuple of classes narrows to the union of those classes. Two limits apply. isinstance cannot check parameterized generics: isinstance(x, list[int]) raises TypeError at runtime, so test against list and the element type stays unknown. Protocols need the @runtime_checkable decorator before isinstance accepts them, and that check only verifies that method names exist.
Exhaustiveness with assert_never
When every union member has its own branch, you can make the checker prove it. assert_never accepts only a value of type Never. If any member is unhandled, the argument still has a real type and the checker reports an error.
from dataclasses import dataclass
from typing import assert_never
@dataclass
class Circle:
radius: float
@dataclass
class Square:
side: float
def area(shape: Circle | Square) -> float:
if isinstance(shape, Circle):
return 3.14159 * shape.radius**2
elif isinstance(shape, Square):
return shape.side**2
else:
assert_never(shape)Add a Triangle to the union later and area fails the check at the assert_never line. Without it, the function would silently return None for triangles at runtime. At runtime assert_never raises an error if reached, so it also guards against bad data.
Custom narrowing with TypeGuard and TypeIs
Sometimes the test is a function you wrote. The checker cannot see inside it, so you declare what a True result means.
from typing import TypeGuard
def is_str_list(items: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(item, str) for item in items)
def join(items: list[object]) -> str:
if is_str_list(items):
return ", ".join(items)
return ""The checker trusts the declaration and does not verify the function body. If the body is wrong, the narrowing is wrong. TypeGuard narrows only the true branch. TypeIs (in typing from Python 3.13, or typing_extensions) also narrows the false branch, so the checker removes the tested type there. It is the better choice when the function is a plain type test on one of the declared members.
When narrowing is lost
Narrowing applies to an expression until something could change it. These cases surprise people:
- Reassignment. After
x = something(), the checker uses the new value's type and forgets the earlier test. - Other expressions. The checker narrows
x,self.x, anda.b.c. It does not narrowd[key]for arbitrary keys or the result of a call. Store it in a local variable first. - Closures and lambdas. A nested function may run after the variable changes. Both checkers keep narrowing only when they can see that the variable is not reassigned after the nested function is defined. Otherwise, copy the value to a new name.
- Method calls. Both checkers keep narrowing of
self.valueacross calls to other methods, even though such a call could reset it. This is a deliberate unsound trade-off, so do not treat it as proof of safety.
A local variable is the dependable fix:
class Box:
def __init__(self, value: int | None) -> None:
self.value = value
def doubled(self) -> int:
value = self.value
if value is None:
return 0
return value * 2The assignment expression (:=) makes the same pattern shorter: if (match := pattern.search(text)) is not None: narrows match inside the block.
Exercise
def f(x: int | str | None) -> int: has the body if not x: return 0, then if isinstance(x, str): return len(x), then return x. What type does the checker give x on the final line, and what bug does the first test hide?
Show answer
After if not x: return 0, the checker removes None. It cannot remove int or str because they have truthy values, so x is int | str. The isinstance(x, str) branch returns, which leaves int on the last line. The bug is that not x also catches 0 and "", so those inputs return 0 before reaching the logic below. For an empty string, the string branch's len(x) would have returned 0 anyway. For 0, the last line would have returned 0 too, so here the results agree. The truthiness test is still the wrong tool when None is the only case you mean to catch.
Exercise
You add a new class Triangle to the Circle | Square union in area. Which line does the checker flag, and why does it flag that line instead of the call sites?
Show answer
It flags assert_never(shape). After the two isinstance branches, shape is still Triangle, not Never. The mismatch appears where the missing case should be handled.