Compare TypeGuard and TypeIs Narrowing
Core idea
TypeGuard tells a checker the type to assume on a true result; its false branch is not narrowed by that guard. TypeIs (Python 3.13+) narrows both branches and requires the narrowed type to be compatible with the input type. Both functions must really return a truthful boolean; annotations alone do not validate values.
from typing import TypeGuarddef all_text(xs:list[object])->TypeGuard[list[str]]: return all(isinstance(x,str) for x in xs)print(all_text(['a','b']),all_text(['a',2]),all_text([]))The empty list satisfies all(); a mutable alias can invalidate the assumption later.
Distinguish union branches
from typing import TypeIsdef is_text(x:str|int)->TypeIs[str]: return isinstance(x,str)def show(x:str|int)->str: if is_text(x): return x.upper() return str(x+1)print(show('ok'),show(8))The checker can narrow x to str in the true branch and int in the false branch.
Common mistake
Do not claim TypeIs[str] for a predicate that rejects some strings, such as a nonempty test. The negative branch would falsely exclude all strings.
Practice
Compare the inferred true and false branch types for a union using both forms in a Python 3.13-capable checker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TypeGuard and TypeIs
Check your understanding of typeguard and typeis.
What is printed?
from typing import TypeGuarddef ints(x:list[object])->TypeGuard[list[int]]: return all(isinstance(i,int) for i in x)print(ints([1,"2"]))What is printed?
from typing import TypeIsdef is_int(x:str|int)->TypeIs[int]: return isinstance(x,int)print(is_int(2),is_int("2"))Which narrows both branches?
Which allows narrowing list[object] to list[str] despite invariance?