Skip to content
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

Infer more specific type after equality or membership check #6027

Closed
jackriccomini opened this issue Dec 7, 2018 · 2 comments
Closed

Infer more specific type after equality or membership check #6027

jackriccomini opened this issue Dec 7, 2018 · 2 comments

Comments

@jackriccomini
Copy link

jackriccomini commented Dec 7, 2018

from typing import Union

def foo(bar: Union[str, int]):
	if bar in ["a", "b", "c"]:
                # to a human, bar is clearly a str. mypy still thinks it's a Union[str, int]
		return bar.upper()
	else:
		return bar
$ mypy test.py 
test.py:5: error: Item "int" of "Union[str, int]" has no attribute "upper"

The same thing happens if the condition is, for example, bar == "a".

  • Are you reporting a bug, or opening a feature request?

Feature request

  • What is the behavior/output you expect?

Mypy to understand the effect of conditions like bar == "a" or bar in ["a"], like it already does with isinstance checks

@jackriccomini jackriccomini changed the title Type is too generic after equality or membership check Not inferring more specific type after equality or membership check Dec 7, 2018
@jackriccomini jackriccomini changed the title Not inferring more specific type after equality or membership check Infer more specific type after equality or membership check Dec 7, 2018
@ilevkivskyi
Copy link
Member

This is not as safe as it looks because of tricky things like:

>>> Decimal(1) in [1, 2, 3]
True

We can probably special-case some builtin types, but this looks like relatively low priority.

@msullivan
Copy link
Collaborator

I think we're probably not going to do this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants