Type narrowing with TypeIs and TypeGuard

suggest change

A variable annotated as int | str can hold either type, but after if isinstance(x, str): a type checker knows that inside the if it is a str. This is called type narrowing. Checkers narrow on isinstance, is None, == against literals, callable(), len() on tuples and on match statements.

Narrowing stops at function boundaries. Moving an isinstance check into a helper function returns a plain bool, and the checker learns nothing from it. Two special return types fix this:

Both are ordinary bool at runtime. All checking is done by a type checker, so the examples show what mypy and pyright report. Examples were run with Python 3.13.15, mypy 2.4.0 and pyright 1.1.414. Absolute paths in the checker output were shortened to the file name.

Unions are explained in Modern union and Optional syntax: X | Y, and the def f[T] syntax used below in Generics with type parameter syntax (PEP 695).

Built-in narrowing

reveal_type() (importable from typing since 3.11) shows what the checker thinks a type is at a given line. At runtime it prints the actual type to stderr and returns its argument:

from typing import reveal_type

def describe(value: int | str | list[int] | None) -> str:
    if value is None:
        reveal_type(value)
        return "nothing"
    reveal_type(value)
    if isinstance(value, str):
        reveal_type(value)
        return f"text of length {len(value)}"
    if isinstance(value, list):
        reveal_type(value)
        return f"list with sum {sum(value)}"
    reveal_type(value)
    return f"number {value + 1}"

for v in [None, "abc", [1, 2, 3], 41]:
    print(describe(v))
Runtime type is 'NoneType'
nothing
Runtime type is 'str'
Runtime type is 'str'
text of length 3
Runtime type is 'list'
Runtime type is 'list'
list with sum 6
Runtime type is 'int'
Runtime type is 'int'
number 42
$ mypy n1.py
n1.py:5: note: Revealed type is "None"
n1.py:7: note: Revealed type is "int | str | list[int]"
n1.py:9: note: Revealed type is "str"
n1.py:12: note: Revealed type is "list[int]"
n1.py:14: note: Revealed type is "int"
Success: no issues found in 1 source file

pyright reports the same types. Every early return removes a type from the union for the rest of the function. By line 14 only int is left, so value + 1 type-checks.

Why a helper function loses narrowing

Move the isinstance check into a function and the narrowing is gone:

def is_str(value: object) -> bool:
    return isinstance(value, str)

def shout(value: int | str) -> str:
    if is_str(value):
        return value.upper()
    return str(value)

print(shout("hi"), shout(5))
HI 5
$ mypy n2.py
n2.py:6: error: Item "int" of "int | str" has no attribute "upper"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

$ pyright n2.py
n2.py:6:22 - error: Cannot access attribute "upper" for class "int"
    Attribute "upper" is unknown (reportAttributeAccessIssue)
1 error, 0 warnings, 0 informations

The checker only knows that is_str returns some bool. It doesn't look at the function body to work out what that bool means. You have to say it in the return type.

TypeGuard: narrowing in the True branch

A function returning TypeGuard[T] is a type predicate. When it returns True, the checker treats its first positional argument as T. The classic use is checking the elements of a container, which isinstance can't do:

from typing import TypeGuard, reveal_type

def is_str_list(items: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in items)

def join_words(items: list[object]) -> str:
    if is_str_list(items):
        reveal_type(items)
        return " ".join(items)
    reveal_type(items)
    return "not all strings"

print(join_words(["type", "guards", "work"]))
print(join_words(["one", 2, "three"]))
Runtime type is 'list'
type guards work
Runtime type is 'list'
not all strings
$ mypy g1.py
g1.py:8: note: Revealed type is "list[str]"
g1.py:10: note: Revealed type is "list[object]"
Success: no issues found in 1 source file

list[str] is not a subtype of list[object], because lists are invariant: you could append an int to a list[object]. TypeGuard doesn't care. It replaces the type with whatever you wrote, and it is up to you that the function body checks it correctly.

In the False branch the type stays what it was. A False result from is_str_list doesn't make items "a list that isn't list[str]" in any useful sense, so this is correct here. It is wrong when the predicate is a plain type test:

from typing import TypeGuard, reveal_type

def is_str(value: object) -> TypeGuard[str]:
    return isinstance(value, str)

def shout(value: int | str) -> str:
    if is_str(value):
        reveal_type(value)
        return value.upper()
    reveal_type(value)
    return str(value + 1)

print(shout("hi"), shout(5))
Runtime type is 'str'
Runtime type is 'int'
HI 6
$ mypy g2.py
g2.py:8: note: Revealed type is "str"
g2.py:10: note: Revealed type is "int | str"
g2.py:11: error: Unsupported operand types for + ("str" and "int")  [operator]
g2.py:11: note: Left operand is of type "int | str"
Found 1 error in 1 file (checked 1 source file)

$ pyright g2.py
g2.py:8:21 - information: Type of "value" is "str"
g2.py:10:17 - information: Type of "value" is "int | str"
g2.py:11:16 - error: Operator "+" not supported for types "int | str" and "Literal[1]"
    Operator "+" not supported for types "str" and "Literal[1]" when expected type is "object" (reportOperatorIssue)
1 error, 0 warnings, 2 informations

We know that a value that is not a str must be an int, but TypeGuard can't express that.

TypeIs: narrowing in both branches

Change TypeGuard to TypeIs and the else branch is narrowed too:

from typing import TypeIs, reveal_type

def is_str(value: object) -> TypeIs[str]:
    return isinstance(value, str)

def shout(value: int | str) -> str:
    if is_str(value):
        reveal_type(value)
        return value.upper()
    reveal_type(value)
    return str(value + 1)

print(shout("hi"), shout(5))
Runtime type is 'str'
Runtime type is 'int'
HI 6
$ mypy i1.py
i1.py:8: note: Revealed type is "str"
i1.py:10: note: Revealed type is "int"
Success: no issues found in 1 source file

$ pyright i1.py
i1.py:8:21 - information: Type of "value" is "str"
i1.py:10:17 - information: Type of "value" is "int"
0 errors, 0 warnings, 2 informations

TypeIs[T] promises more than TypeGuard[T]: the function returns True if and only if the argument is a T. Because of that promise, TypeIs has a rule that TypeGuard doesn't have: T must be consistent with the parameter type. The invariant list example from above is rejected:

from typing import TypeIs

def is_str_list(items: list[object]) -> TypeIs[list[str]]:
    return all(isinstance(x, str) for x in items)
$ mypy i2.py
i2.py:3: error: Narrowed type "list[str]" is not a subtype of input type "list[object]"  [narrowed-type-not-subtype]
Found 1 error in 1 file (checked 1 source file)

$ pyright i2.py
i2.py:3:41 - error: Return type of TypeIs ("list[str]") is not consistent with value parameter type ("list[object]") (reportGeneralTypeIssues)
1 error, 0 warnings, 0 informations

So container checks like this one stay with TypeGuard. If you can change the parameter to a read-only type such as Sequence[object], TypeIs[Sequence[str]] is accepted, because Sequence is covariant.

TypeIs keeps what is already known

The second difference is in the True branch. TypeGuard[T] replaces the argument's type with T. TypeIs[T] intersects the two, like isinstance does, so precise types survive:

from collections.abc import Sequence
from typing import Any, TypeGuard, TypeIs, reveal_type

def guard_seq(value: object) -> TypeGuard[Sequence[Any]]:
    return isinstance(value, Sequence) and not isinstance(value, str)

def is_seq(value: object) -> TypeIs[Sequence[Any]]:
    return isinstance(value, Sequence) and not isinstance(value, str)

def first_guard(value: list[int] | tuple[str, ...] | int) -> object:
    if guard_seq(value):
        reveal_type(value)
        return value[0]
    return value

def first_is(value: list[int] | tuple[str, ...] | int) -> object:
    if is_seq(value):
        reveal_type(value)
        return value[0]
    reveal_type(value)
    return value

print(first_guard([1, 2]), first_is(("a", "b")), first_is(7))
Runtime type is 'list'
Runtime type is 'tuple'
Runtime type is 'int'
1 a 7
$ mypy i3.py
i3.py:12: note: Revealed type is "typing.Sequence[Any]"
i3.py:18: note: Revealed type is "list[int] | tuple[str, ...]"
i3.py:20: note: Revealed type is "int"
Success: no issues found in 1 source file

With TypeGuard, value[0] is Any, and the checker has forgotten that it was a list[int] or a tuple[str, ...]. With TypeIs, the list[int] | tuple[str, ...] part of the union is kept, and the rest (int) goes to the else branch.

A TypeIs that lies

The checker trusts the "if and only if" promise and never checks the function body. A TypeIs predicate that tests more than the type breaks the else branch:

from typing import TypeIs

def is_positive(value: int | str) -> TypeIs[int]:
    return isinstance(value, int) and value > 0

def label(value: int | str) -> str:
    if is_positive(value):
        return f"+{value}"
    return value.upper()

print(label(5))
print(label("abc"))
print(label(-3))
+5
ABC
Traceback (most recent call last):
  File "i4.py", line 13, in <module>
    print(label(-3))
          ~~~~~^^^^
  File "i4.py", line 9, in label
    return value.upper()
           ^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'upper'
$ mypy i4.py
Success: no issues found in 1 source file

$ pyright i4.py
0 errors, 0 warnings, 0 informations

-3 is an int, but is_positive(-3) returns False, so the checker concludes that value is a str in the last line. Neither checker notices. The fix is to declare is_positive with TypeGuard[int]: then the else branch stays int | str and the checker flags value.upper().

Choosing between them

TypeGuard[T] TypeIs[T]
Added in 3.10 3.13
True branch type becomes T type becomes intersection of the old type and T
False branch not narrowed narrowed to "not T"
T must be a subtype of the parameter type no yes
Function must return True for every T no yes

Use TypeIs for "is this value of type T?" checks, which covers most predicates. Use TypeGuard when the predicate also checks values (positive, non-empty, short enough) or when it narrows to a type that is not a subtype of the input, as with list[object] to list[str].

Narrowing str to Literal

A common practical case is validating a string against a closed set of values. Here mypy and pyright behave differently with plain in, while a TypeIs predicate works in both:

from typing import Literal, TypeIs, get_args, reveal_type

type Mode = Literal["r", "w", "a"]
MODES: tuple[str, ...] = get_args(Mode.__value__)

def parse_mode_naive(text: str) -> Mode:
    if text in ("r", "w", "a"):
        reveal_type(text)
        return text
    raise ValueError(f"bad mode {text!r}")

def is_mode(text: str) -> TypeIs[Mode]:
    return text in MODES

def parse_mode(text: str) -> Mode:
    if is_mode(text):
        reveal_type(text)
        return text
    raise ValueError(f"bad mode {text!r}, expected one of {MODES}")

print(MODES)
print(parse_mode("w"))
print(parse_mode("rw"))
('r', 'w', 'a')
w
Traceback (most recent call last):
  File "l1.py", line 23, in <module>
    print(parse_mode("rw"))
          ~~~~~~~~~~^^^^^^
  File "l1.py", line 19, in parse_mode
    raise ValueError(f"bad mode {text!r}, expected one of {MODES}")
ValueError: bad mode 'rw', expected one of ('r', 'w', 'a')
$ mypy l1.py
l1.py:8: note: Revealed type is "str"
l1.py:9: error: Incompatible return value type (got "str", expected "Literal['r', 'w', 'a']")  [return-value]
l1.py:17: note: Revealed type is "Literal['r'] | Literal['w'] | Literal['a']"
Found 1 error in 1 file (checked 1 source file)

$ pyright l1.py
l1.py:8:21 - information: Type of "text" is "Literal['r', 'w', 'a']"
l1.py:17:21 - information: Type of "text" is "Literal['r', 'w', 'a']"
0 errors, 0 warnings, 2 informations

pyright narrows str to a Literal on in with a tuple of literals, mypy doesn't. get_args reads the allowed values from the Literal itself (through __value__, since Mode is a type alias), so the list of modes is written only once. Literal and exhaustiveness checks are covered in more depth in the "Protocols, Literal and Final" article of this chapter.

Generic predicates, extra arguments and methods

Only the first positional argument is narrowed, but a predicate can take more arguments, can be generic, and can be a method (then the first argument after self or cls is narrowed):

from typing import TypeGuard, TypeIs, reveal_type

def is_list_of[T](items: list[object], tp: type[T]) -> TypeGuard[list[T]]:
    return all(isinstance(x, tp) for x in items)

def is_pair_of[T](value: tuple[object, ...], tp: type[T]) -> TypeGuard[tuple[T, T]]:
    return len(value) == 2 and all(isinstance(x, tp) for x in value)

class Validator:
    def __init__(self, max_len: int) -> None:
        self.max_len = max_len

    def is_short_str(self, value: object) -> TypeGuard[str]:
        return isinstance(value, str) and len(value) <= self.max_len

def demo(items: list[object], point: tuple[object, ...], name: object) -> None:
    if is_list_of(items, int):
        reveal_type(items)
        print("sum:", sum(items))
    if is_pair_of(point, float):
        reveal_type(point)
        x, y = point
        print("distance:", (x * x + y * y) ** 0.5)
    if Validator(max_len=8).is_short_str(name):
        reveal_type(name)
        print("name:", name.title())

demo([1, 2, 3], (3.0, 4.0), "ada lovelace")
demo(["1"], (1.0,), "grace")
Runtime type is 'list'
sum: 6
Runtime type is 'tuple'
distance: 5.0
Runtime type is 'str'
name: Grace
$ mypy p1.py
p1.py:18: note: Revealed type is "list[int]"
p1.py:21: note: Revealed type is "tuple[float, float]"
p1.py:25: note: Revealed type is "str"
Success: no issues found in 1 source file

is_short_str uses TypeGuard on purpose: a long string makes it return False, so the else branch must not be narrowed to "not a str".

The narrowed argument doesn't have to be a plain variable. Attribute access and subscripts with literal keys are narrowed as well:

from dataclasses import dataclass
from typing import TypeIs, reveal_type

def is_int(value: object) -> TypeIs[int]:
    return isinstance(value, int)

@dataclass
class Cell:
    raw: int | str

def check(cell: Cell, cells: dict[str, int | str]) -> None:
    if is_int(cell.raw):
        reveal_type(cell.raw)
    if is_int(cells["a"]):
        reveal_type(cells["a"])

check(Cell(1), {"a": 2})
print(is_int(True), is_int("1"), type(is_int(2)))
print(is_int.__annotations__["return"])
Runtime type is 'int'
Runtime type is 'int'
True False <class 'bool'>
typing.TypeIs[int]
$ mypy r1.py
r1.py:13: note: Revealed type is "int"
r1.py:15: note: Revealed type is "int"
Success: no issues found in 1 source file

The last two lines show the runtime side. The predicate returns an ordinary bool (and True counts as an int, since bool is a subclass of int). TypeIs[int] is just an annotation object that Python never looks at.

Narrowing in match statements

match (Python 3.10) narrows in each case. A class pattern works like isinstance, a literal pattern like ==, and each case removes what it matched from the cases below it:

from dataclasses import dataclass
from typing import assert_never, reveal_type

@dataclass
class Circle:
    radius: float

@dataclass
class Rect:
    width: float
    height: float

@dataclass
class Triangle:
    base: float
    height: float

type Shape = Circle | Rect | Triangle

def area(shape: Shape) -> float:
    match shape:
        case Circle(radius=r):
            reveal_type(shape)
            return 3.14159 * r * r
        case Rect(width=w, height=h) if w == h:
            reveal_type(shape)
            return w * w
        case Rect(width=w, height=h):
            return w * h
        case _:
            reveal_type(shape)
            return 0.5 * shape.base * shape.height

def describe(value: int | str | list[int] | None) -> str:
    match value:
        case None:
            return "nothing"
        case int(n) if n < 0:
            reveal_type(n)
            return "negative"
        case int() | str():
            reveal_type(value)
            return f"scalar {value!r}"
        case [first, *rest]:
            reveal_type(first)
            reveal_type(rest)
            return f"list starting with {first}"
        case list():
            return "empty list"
        case _:
            assert_never(value)

print(area(Circle(1)), area(Rect(2, 2)), area(Rect(2, 3)), area(Triangle(4, 3)))
for v in [None, -1, 7, "x", [1, 2, 3], []]:
    print(describe(v))
3.14159 4 6 6.0
nothing
negative
scalar 7
scalar 'x'
list starting with 1
empty list

(The "Runtime type is" lines that reveal_type writes to stderr were left out.)

$ mypy m2.py
m2.py:23: note: Revealed type is "m2.Circle"
m2.py:26: note: Revealed type is "m2.Rect"
m2.py:31: note: Revealed type is "m2.Triangle"
m2.py:39: note: Revealed type is "int"
m2.py:42: note: Revealed type is "int | str"
m2.py:45: note: Revealed type is "int"
m2.py:46: note: Revealed type is "list[int]"
Success: no issues found in 1 source file

Note these points:

Sequence patterns don't fully narrow. If the last list case is written as case []: instead of case list():, the checkers can't tell that [first, *rest] and [] cover every list:

def kind(value: int | list[int]) -> str:
    match value:
        case int():
            return "int"
        case [first, *rest]:
            return f"list starting with {first}"
        case []:
            return "empty list"
$ mypy m3.py
m3.py:1: error: Missing return statement  [return]
Found 1 error in 1 file (checked 1 source file)

$ pyright m3.py
m3.py:1:37 - error: Function with declared return type "str" must return value on all code paths
    "None" is not assignable to "str" (reportReturnType)
1 error, 0 warnings, 0 informations

End such a match with a class pattern (case list():) or a case _:.

You can also call a predicate in a guard. case str() if is_mode(value): narrows value to Mode inside that case.

Other narrowing forms

Checkers recognize a few more expressions. Tuples of different lengths narrow on len(), classes with a Literal tag attribute narrow on == against the tag (a "discriminated union"), and callable() separates functions from other values:

from collections.abc import Callable
from dataclasses import dataclass
from typing import Literal, reveal_type

def point_len(p: tuple[int, int] | tuple[int, int, int]) -> int:
    if len(p) == 2:
        reveal_type(p)
        return 2
    reveal_type(p)
    return 3

@dataclass
class Ok:
    value: int
    kind: Literal["ok"] = "ok"

@dataclass
class Err:
    message: str
    kind: Literal["err"] = "err"

def show(result: Ok | Err) -> str:
    if result.kind == "ok":
        reveal_type(result)
        return f"ok: {result.value}"
    reveal_type(result)
    return f"error: {result.message}"

def run(task: Callable[[], int] | int) -> int:
    if callable(task):
        reveal_type(task)
        return task()
    reveal_type(task)
    return task

print(point_len((1, 2, 3)), show(Ok(1)), show(Err("boom")), run(lambda: 4), run(5))
Runtime type is 'tuple'
Runtime type is 'Ok'
Runtime type is 'Err'
Runtime type is 'function'
Runtime type is 'int'
3 ok: 1 error: boom 4 5
$ mypy o1.py
o1.py:7: note: Revealed type is "tuple[int, int]"
o1.py:9: note: Revealed type is "tuple[int, int, int]"
o1.py:24: note: Revealed type is "o1.Ok"
o1.py:26: note: Revealed type is "o1.Err"
o1.py:31: note: Revealed type is "def () -> int"
o1.py:33: note: Revealed type is "int"
Success: no issues found in 1 source file

The same tag-based narrowing works for dictionaries described by TypedDict, which has its own article in this chapter.

Narrowing is not invalidated by function calls

Narrowing of attributes is optimistic. A call made in between could change the attribute, but checkers keep the narrowed type anyway:

class User:
    def __init__(self, email: str | None) -> None:
        self.email = email

def unsubscribe(user: User) -> None:
    user.email = None

def notify(user: User) -> None:
    if user.email is not None:
        unsubscribe(user)
        print(user.email.lower())

notify(User("Ann@example.com"))
Traceback (most recent call last):
  File "c2.py", line 13, in <module>
    notify(User("Ann@example.com"))
    ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c2.py", line 11, in notify
    print(user.email.lower())
          ^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'lower'
$ mypy c2.py
Success: no issues found in 1 source file

$ pyright c2.py
0 errors, 0 warnings, 0 informations

Re-checking after every call would make narrowing of attributes almost useless, so both checkers accept this trade-off. If the code between the check and the use can modify the object, copy the value into a local variable first (email = user.email) and narrow that.

Older Python versions: typing_extensions

TypeIs is available on older Pythons from the typing_extensions package (since version 4.10). Type checkers treat it like typing.TypeIs:

import sys
from typing import Union

from typing_extensions import TypeIs

def is_str(value: object) -> TypeIs[str]:
    return isinstance(value, str)

def shout(value: Union[int, str]) -> str:
    if is_str(value):
        return value.upper()
    return str(value + 1)

print(sys.version.split()[0], shout("hi"), shout(5))
print(is_str.__annotations__)
3.10.11 HI 6
{'value': <class 'object'>, 'return': typing_extensions.TypeIs[str]}

This was run with Python 3.10 and typing_extensions 4.16.0. TypeGuard is in typing since 3.10, and typing_extensions also has it for 3.9 and older.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents