|
| 1 | +# Narrowing with assert statements |
| 2 | + |
| 3 | +## `assert` a value `is None` or `is not None` |
| 4 | + |
| 5 | +```py |
| 6 | +def _(x: str | None, y: str | None): |
| 7 | + assert x is not None |
| 8 | + reveal_type(x) # revealed: str |
| 9 | + assert y is None |
| 10 | + reveal_type(y) # revealed: None |
| 11 | +``` |
| 12 | + |
| 13 | +## `assert` a value is truthy or falsy |
| 14 | + |
| 15 | +```py |
| 16 | +def _(x: bool, y: bool): |
| 17 | + assert x |
| 18 | + reveal_type(x) # revealed: Literal[True] |
| 19 | + assert not y |
| 20 | + reveal_type(y) # revealed: Literal[False] |
| 21 | +``` |
| 22 | + |
| 23 | +## `assert` with `is` and `==` for literals |
| 24 | + |
| 25 | +```py |
| 26 | +from typing import Literal |
| 27 | + |
| 28 | +def _(x: Literal[1, 2, 3], y: Literal[1, 2, 3]): |
| 29 | + assert x is 2 |
| 30 | + reveal_type(x) # revealed: Literal[2] |
| 31 | + assert y == 2 |
| 32 | + reveal_type(y) # revealed: Literal[1, 2, 3] |
| 33 | +``` |
| 34 | + |
| 35 | +## `assert` with `isinstance` |
| 36 | + |
| 37 | +```py |
| 38 | +def _(x: int | str): |
| 39 | + assert isinstance(x, int) |
| 40 | + reveal_type(x) # revealed: int |
| 41 | +``` |
| 42 | + |
| 43 | +## `assert` a value `in` a tuple |
| 44 | + |
| 45 | +```py |
| 46 | +from typing import Literal |
| 47 | + |
| 48 | +def _(x: Literal[1, 2, 3], y: Literal[1, 2, 3]): |
| 49 | + assert x in (1, 2) |
| 50 | + reveal_type(x) # revealed: Literal[1, 2] |
| 51 | + assert y not in (1, 2) |
| 52 | + reveal_type(y) # revealed: Literal[3] |
| 53 | +``` |
0 commit comments