python / python/mypy

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

オープン
#19,255 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug topic-type-narrowing topic-type-variables
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提供された Python の例を mypy v1.16 で、mypy playground またはローカルの checkout を使って実行します。final class A のインスタンスの narrowing が、A | int に bound された TypeVar U とどのように相互作用するかを調査します。例が incompatible return value error なしで型チェックに通れば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。