Skip to content

Infer more specific type after equality or membership check #6027

Closed

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

Activity

  1. changed the title [-]Type is too generic after equality or membership check[/-] [+]Not inferring more specific type after equality or membership check[/+] on Dec 7, 2018
  2. changed the title [-]Not inferring more specific type after equality or membership check[/-] [+]Infer more specific type after equality or membership check[/+] on Dec 7, 2018
  3. ilevkivskyi commented on Dec 7, 2018

    @ilevkivskyi
    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.

  4. msullivan commented on Jan 28, 2020

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions