python / python/mypy

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

Open
#19,530 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied scratch.py reproducer with mypy 1.17.0 and confirming the [return-value] error. Trace the type-narrowing and generic return-value handling involved in the isinstance(o, Foo) branch, then add a regression test for this example. Done means the test passes without the incompatible return-value error and existing tests remain green.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.