Skip to content

Type narrowing of TypeVar with abstract bases classes causes [return-value] error #19530

@crazyscientist

Description

@crazyscientist

I'd like to take the case of #15151 two steps further. Instead of dealing with a plain generic type, let's consider the use of a Generic in combination with inheritance.

Bug Report

mypy reports a type incompatibility error when the TypeVars are narrowed within a generic function but the generic arg is not changed in any way.

To Reproduce

import abc
from typing import TypeVar


T = TypeVar("T")


class Base[T](abc.ABC):
    @abc.abstractmethod
    def foo(self) -> T: ...


class Foo(Base[str]):
    def foo(self) -> str:
        return "foo"


def foo(o: Base[T]) -> T:
    if isinstance(o, Foo):
        return o.foo()

    return o.foo()


if __name__ == "__main__":
    foo(Foo())

Expected Behavior

No errors are thrown since the parameterization of the TypeVar happens via the subclass. During type narrowing, the narrowed type should be considered in both places: the argument and return value.

Actual Behavior

scratch.py:20: error: Incompatible return value type (got "str", expected "T")  [return-value]

Your Environment

  • Mypy version used: 1.17.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions