KEMBAR78
Type narrowing broken with negative integer literals · Issue #10514 · python/mypy · GitHub
Skip to content

Type narrowing broken with negative integer literals #10514

@svenpanne

Description

@svenpanne

Bug Report
Type narrowing seems to be broken for negative integer literals. Wild guess: This probably happens because they are not a single entity, but a unary minus applied to a positive integer. Funnily enough, the non-overlapping equality check seems to get this right.

To Reproduce
Consider the following code:

from typing import Literal, Union

Foo = Union[Literal[-1], Literal[42]]


def correct(f: Foo) -> None:
    if f == 42:
        reveal_type(f)  # Revealed type is 'Literal[42]'
    else:
        reveal_type(f)  # Revealed type is 'Literal[-1]'


def also_correct(f: Foo) -> None:
    if f == -2:
        reveal_type(f)  # Non-overlapping equality check (left operand type: "Union[Literal[-1], Literal[42]]", right operand type: "Literal[-2]")
    else:
        reveal_type(f)  # Revealed type is 'Union[Literal[-1], Literal[42]]'


def wrong(f: Foo) -> None:
    if f == -1:
        reveal_type(f)  # Revealed type is '<nothing>'
    else:
        reveal_type(f)  # Revealed type is 'Union[Literal[-1], Literal[42]]'

Expected Behavior
The revealed types in wrong should be the same as in correct, only swapped.

Actual Behavior
Mypy is confused. 😉

Your Environment

  • Mypy version used: 0.812
  • Python version used: 3.8.10

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions