Wrong inference for `abs/__abs__` or function that calls a method on a generic type.
オープン
まだ誰も着手していません。
bug
topic-type-variables
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- 平均マージ
- 1日 18時間
- マージ済み PR(30日)
- 54
説明
This was discussed in the typing forums.
Here mypy (latest version 1.17.1) infers the type of abs(value) incorrectly:
from typing import Self
class Real:
def __abs__(self) -> Self:
return self
def my_abs[T: Real](value: T):
reveal_type(abs(value)) # Real
reveal_type(value.__abs__()) # T
That is:
$ mypy z.py
z.py:8: note: Revealed type is "z.Real"
z.py:9: note: Revealed type is "T`-1"
Success: no issues found in 1 source file
Since abs just calls __abs__ they return the same type which should be inferred as T in both cases.
I show the simpler example above with a concrete Real type but what I actually want to do is have a Protocol for abs:
from typing import Self, Protocol
class HasAbs(Protocol):
def __abs__(self) -> Self:
return self
def my_abs[T: HasAbs](value: T) -> T:
return abs(value)
However mypy incorrectly rejects this because it infers the type of abs(value) incorrectly:
$ mypy z.py
z.py:8: error: Incompatible return value type (got "HasAbs", expected "T") [return-value]
Found 1 error in 1 file (checked 1 source file)
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
issue にある z.py の例から始め、mypy 1.17.1 を実行して、異なる reveal された型と拒否される戻り値を再現します。abs(value) と value.abs() がそれぞれどのように推論されるかを追跡し、HasAbs に制約されたジェネリックな値が型 T を保持して型チェックに通ることを示す回帰テストを追加します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100