GeezerVison is showing github.com — Type not narrowed correctly for `if X in collection` · Issue #3229 · python/mypy
Type not narrowed correctly for if X in collection #3229Descriptiondef 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 Reacted by Nicholas Larus-Stone, Anton Agestam, Allison Karlitskaya, wyattscarpenter, darkdragon-001 and Marc Bresson Activityilevkivskyi 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 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. added a commit that references this issue on Jul 24, 2024This issue will close once commit ed0cd4a is merged into the 'master' branch.ed0cd4a 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 commented on Oct 10, 2024 @Jordandev678 Sure! The original PR can be resubmitted once the issues have been addressed.
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|