Sub topic 6
Narrowing types with isinstance, None checks, and conditions
This chapter assumes you can annotate functions, run mypy or Pyright, and read a union type such as str | None. Narrowing is how a checker turns a wide union into a specific type inside part of a function.
What narrowing does
A checker follows the control flow of your code. After a test like x is None, it knows more about x in each branch and uses that to accept or reject operations.
Checks the tools understand
Both mypy and Pyright narrow on these forms:
x is Noneandx is not Noneisinstance(x, SomeClass), including tuples of classes- Truthiness tests such as
if x: - Equality with literals, such as
if mode == "r":whenmodeis aLiteraltype intests against a collection of literalscallable(x)
def describe(value: int | str | list[int]) -> str:
if isinstance(value, int):
return f"int {value + 1}"
elif isinstance(value, str):
return value.upper()
reveal_type(value) # list[int]
return f"list of {len(value)}"Each branch removes one member of the union. In the final lines, only list[int] is left.
Early returns and assert
You don't need an else. Code after an early return, raise, or continue is narrowed by the failed test.
def load(path: str | None) -> str:
if path is None:
raise ValueError("path is required")
return path.strip() # path is str hereAn assert x is not None also narrows. Python removes asserts when run with -O, so use them for facts you know to be true and not for validating input.
Truthiness can narrow too much
def label(text: str | None) -> str:
if text:
return text
return "missing"This type checks, but "" is also falsy, so an empty string gets the label "missing". If None is the only case you mean to handle, write text is None.
Why narrowing sometimes disappears
Narrowing lasts only while the checker can prove the variable has not changed. Common ways to lose it:
- Reassigning the variable after the check.
- Checking
self.nameand then using it after other code runs. Copy it to a local variable first:name = self.name. - Using a check the checker does not recognize, such as
if is_valid(x):with a custom helper.
For custom helpers, annotate the return type as TypeGuard[...] or TypeIs[...]. The helper then tells the checker what a True result means. TypeIs is in typing from Python 3.13, and typing_extensions provides it for older versions.
Checking your understanding
Exercise
In the function below, the checker reports an error on the last line. What is the error, and how do you fix it without changing the signature? def size(items: list[int] | None) -> int: if items is not None: print("got items") return len(items)
Show answer
After the if block, items is still list[int] | None, because the None case falls through to the return. len(None) is an error. Fix it by returning early: "if items is None: return 0", then "return len(items)". Raising an exception in the None case also works.