Incompatible return value type when using typevar with bound and self returning method
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- 平均マージ
- 1日 18時間
- マージ済み PR(30日)
- 54
説明
Bug Report
Using a typevar bound to a class that has a self returning method leads to an error when using in a function that operates on the typevar and returns the typevar.
Using constraint does not present the issue but looses the generic on the class.
To Reproduce
# pyright: strict
from typing import Any, Generic, TypeVar
from typing_extensions import Self, reveal_type
T = TypeVar("T")
class X(Generic[T]):
def m(self, v: int) -> Self:
return self
class Y:
def m(self, v: int) -> Self:
return self
# using bound: tb_self errors with Incompatible return value type
TB = TypeVar("TB", bound=X[Any] | Y)
def tb_self(value: TB) -> TB:
return value.m(42)
def tb(value: TB) -> TB:
return value
reveal_type(tb_self(X[int]()))
reveal_type(tb(X[int]()))
# using constraint: return type is X[Any] in both cases
TC = TypeVar("TC", X[Any], Y)
def tc_self(value: TC) -> TC:
return value.m(42)
def tc(value: TC) -> TC:
return value
reveal_type(tc_self(X[int]()))
reveal_type(tc(X[int]()))
https://gist.github.com/mypy-play/3f911f7de9e2282fb6463a7146ffae47
The output is:
file.py:20:12: error: Incompatible return value type (got "X[Any] | Y", expected "TB") [return-value]
file.py:25:13: note: Revealed type is "try_.X[builtins.int]"
file.py:26:13: note: Revealed type is "try_.X[builtins.int]"
file.py:37:13: note: Revealed type is "try_.X[Any]"
file.py:38:13: note: Revealed type is "try_.X[Any]"
Found 1 error in 1 file (checked 1 source file)
For reference pyright on the same input reports no error
Expected Behavior
The is no error.
Actual Behavior
Mypy reports an error when the using a self returning method
Your Environment
- Mypy version used: 1.9.0, 1.7.1
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): - - Python version used: 3.10, 3.12
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、提供された例を mypy 1.9.0 と指定された Python バージョンで再現し、その後、束縛された TypeVar のケースと制約付きの TypeVar のケース、およびそれぞれの reveal された型を比較します。完了条件は、self を返すメソッドが互換性のない戻り値に関する診断を生成せず、期待される reveal 出力に示されたジェネリック型を維持することです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 38/100