KEMBAR78
Value-Constrained TypeVar incorrectly narrowed down by isinstance checks · Issue #10302 · python/mypy · GitHub
Skip to content

Value-Constrained TypeVar incorrectly narrowed down by isinstance checks #10302

@wpeale

Description

@wpeale

Bug Report

When using a TypeVar with a value restriction to multiple classes, isinstance checks seem to incorrectly narrow down the TypeVar. Possibly connected to #10287

To Reproduce

from typing import TypeVar


class A:
    pass


class B:
    pass


OperableT = TypeVar(
    "OperableT",
    A,
    B,
)


class Operator:
    def process(self, obj: OperableT) -> OperableT:
        if isinstance(obj, A):
            return A()
        elif isinstance(obj, B):
            return B()

Expected Behavior

Mypy should be able to resolve the type of the OperableT TypeVar and correctly validate the return value in the process() method.

Actual Behavior

Mypy instead throws a return error for the above:
error: Incompatible return value type (got "A", expected "B") [return-value]

For some reason, in the first isinstance check, mypy seems to resolve the OperableT TypeVar to "B" instead of "A."

  • Mypy version used: 0.770 (tested also with 0.812)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8.2
  • Operating system and version: Ubuntu 20.04

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions