Skip to content

Infer more specific type after equality or membership check #6027

Closed
@jackriccomini

Description

@jackriccomini
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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions