-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Type not narrowed correctly for if X in collection
#3229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Than you for reporting this! I have also encountered situations where this could be useful. It is not super easy to implement, but I think this is a reasonable feature to support (especially for invariant collections, where the type is known precisely). As a workaround, you could add |
I just realised: there might also have to be a special case for testing if a float is in a set of ints, or any other situation where |
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 <20153053+Jordandev678@users.noreply.github.com>
Reopening, since the original implementation was reverted due to some issues (#17864). |
@JukkaL want me to pick this up? |
@Jordandev678 Sure! The original PR can be resubmitted once the issues have been addressed. |
The revealed type is
Union[builtins.str, builtins.float]
but should bebuiltins.str
The text was updated successfully, but these errors were encountered: