mypy icon indicating copy to clipboard operation
mypy copied to clipboard

An instance of a final class should be treated as satisfying a TypeVar bound to it, after being narrowed

Open A5rocks opened this issue 7 months ago • 0 comments

Bug Report

See title, I think this is the cause of the remaining issue for https://github.com/python/mypy/issues/9424. I think this is a followup to https://github.com/python/mypy/pull/19183.

To Reproduce

from typing import TypeVar, final

@final
class A:
    pass

U = TypeVar('U', bound=A | int)

def f(u: U) -> U:
    if isinstance(u, A):
        return A()
    else:
        return u

Expected Behavior

No errors

Actual Behavior

There's an error:

main.py:11: error: Incompatible return value type (got "A", expected "U")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

Reproduced on mypy play.

  • Mypy version used: v1.16
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

A5rocks avatar Jun 08 '25 20:06 A5rocks