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.
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.
Activity
ilevkivskyi commented on Apr 24, 2017
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.
elazarg commented on Apr 25, 2017
Related #2357 #1203
frexvahi commented on Aug 28, 2019
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.
Add test case from python#3229
Narrow based on collection containment (#17344)
JukkaL commented on Oct 2, 2024
Reopening, since the original implementation was reverted due to some issues (#17864).
Jordandev678 commented on Oct 9, 2024
@JukkaL want me to pick this up?
JukkaL commented on Oct 10, 2024
@Jordandev678 Sure! The original PR can be resubmitted once the issues have been addressed.
Narrow types based on collection containment (python#20602)