python / python/mypy

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

Open
#19,255 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

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

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 provided Python example with mypy v1.16, using the mypy playground or a local checkout. Investigate how narrowing an instance of the final class A interacts with the TypeVar U bound to A | int. Done means the example type-checks without the incompatible return value error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.