-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[red-knot] Add narrowing for 'while' loops (#14947)
## Summary Add type narrowing for `while` loops and corresponding `else` branches. closes #14861 ## Test Plan New Markdown tests.
- Loading branch information
Showing
3 changed files
with
61 additions
and
1 deletion.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
crates/red_knot_python_semantic/resources/mdtest/narrow/while.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# Narrowing in `while` loops | ||
|
||
We only make sure that narrowing works for `while` loops in general, we do not exhaustively test all | ||
narrowing forms here, as they are covered in other tests. | ||
|
||
Note how type narrowing works subtly different from `if` ... `else`, because the negated constraint | ||
is retained after the loop. | ||
|
||
## Basic `while` loop | ||
|
||
```py | ||
def next_item() -> int | None: ... | ||
|
||
x = next_item() | ||
|
||
while x is not None: | ||
reveal_type(x) # revealed: int | ||
x = next_item() | ||
|
||
reveal_type(x) # revealed: None | ||
``` | ||
|
||
## `while` loop with `else` | ||
|
||
```py | ||
def next_item() -> int | None: ... | ||
|
||
x = next_item() | ||
|
||
while x is not None: | ||
reveal_type(x) # revealed: int | ||
x = next_item() | ||
else: | ||
reveal_type(x) # revealed: None | ||
|
||
reveal_type(x) # revealed: None | ||
``` | ||
|
||
## Nested `while` loops | ||
|
||
```py | ||
from typing import Literal | ||
|
||
def next_item() -> Literal[1, 2, 3]: ... | ||
|
||
x = next_item() | ||
|
||
while x != 1: | ||
reveal_type(x) # revealed: Literal[2, 3] | ||
|
||
while x != 2: | ||
# TODO: this should be Literal[1, 3]; Literal[3] is only correct | ||
# in the first loop iteration | ||
reveal_type(x) # revealed: Literal[3] | ||
x = next_item() | ||
|
||
x = next_item() | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters