Type not narrowed correctly for `if X in collection`
def foobar(foo: Union[str, float]):
if foo in ['fizz', 'buzz']:
reveal_type(foo)
else:
pass
The revealed type is Union[builtins.str, builtins.float] but should be builtins.str
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 assert isinstance(foo, str) in the if-branch, mypy will recognize this.
Related #2357 #1203
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 a == b can be true even though type(a) == type(b) is not.
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.