Skip to content

Infer more specific type after equality or membership check #6027

Description

@jackriccomini
fromtypingimportUniondeffoo(bar: Union[str, int]):
ifbarin ["a", "b", "c"]:
# to a human, bar is clearly a str. mypy still thinks it's a Union[str, int]returnbar.upper()
else:
returnbar
$ 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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions