You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Enables the narrowing of variable types when checking a variable is "in"
a collection, and the collection type is a subtype of the variable type.
Fixes#3229
This PR updates the type narrowing for the "in" operator and allows it
to narrow the type of a variable to the type of the collection's items -
if the collection item type is a subtype of the variable (as defined by
is_subtype).
Examples
```python
def foobar(foo: Union[str, float]):
if foo in ['a', 'b']:
reveal_type(foo) # N: Revealed type is "builtins.str"
else:
reveal_type(foo) # N: Revealed type is "Union[builtins.str, builtins.float]"
```
```python
typ: List[Literal['a', 'b']] = ['a', 'b']
x: str = "hi!"
if x in typ:
reveal_type(x) # N: Revealed type is "Union[Literal['a'], Literal['b']]"
else:
reveal_type(x) # N: Revealed type is "builtins.str"
```
One existing test was updated, which compared `Optional[A]` with "in" to
`(None,)`. Piror to this change that resulted in `Union[__main__.A,
None]`, which now narrows to `None`. Test cases have been added for
"in", "not in", Sets, Lists, and Tuples.
I did add to the existing narrowing.pyi fixture for the test cases. A
search of the *.test files shows it was only used in the narrowing
tests, so there shouldn't be any speed impact in other areas.
---------
Co-authored-by: Jordandev678 <[email protected]>
0 commit comments