mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Type not narrowed correctly for `if X in collection`

Open frexvahi opened this issue 8 years ago • 6 comments

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

frexvahi avatar Apr 24 '17 09:04 frexvahi

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.

ilevkivskyi avatar Apr 24 '17 09:04 ilevkivskyi

Related #2357 #1203

elazarg avatar Apr 25 '17 20:04 elazarg

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.

frexvahi avatar Aug 28 '19 15:08 frexvahi

Reopening, since the original implementation was reverted due to some issues (#17864).

JukkaL avatar Oct 02 '24 14:10 JukkaL

@JukkaL want me to pick this up?

Jordandev678 avatar Oct 09 '24 20:10 Jordandev678

@Jordandev678 Sure! The original PR can be resubmitted once the issues have been addressed.

JukkaL avatar Oct 10 '24 08:10 JukkaL