python / python/mypy

Arithmetic with type variables fails to typecheck ("Unsupported operand types")

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

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

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

説明

To Reproduce

from typing import Protocol, TypeVar
from typing_extensions import Self

class A(Protocol):
    def __add__(self, other: int | Self) -> Self: ...
    def __radd__(self, other: int | Self) -> Self: ...


AT = TypeVar("AT", bound=int | A)
# OK:
# AT = TypeVar("AT", int, A)


def f(a: AT) -> None:
    a + a

https://mypy-play.net/?mypy=latest&python=3.12&gist=13a490c6b5b075de398e0c84736fd194

Expected Behavior

It's a little weird that there is a lone type variable, but all cases of the operator application should be covered, so IMO this should typecheck OK. pyright agrees:

WARNING: there is a new pyright version available (v1.1.388 -> v1.1.389).
Please install the new version or set PYRIGHT_PYTHON_FORCE_VERSION to `latest`

/home/andreas/tmp/mypy-arith.py
  /home/andreas/tmp/mypy-arith.py:14:10 - warning: TypeVar "AT" appears only once in generic function signature
    Use "int | A" instead (reportInvalidTypeVarUse)
  /home/andreas/tmp/mypy-arith.py:15:5 - warning: Expression value is unused (reportUnusedExpression)
0 errors, 2 warnings, 0 informations

Actual Behavior

mypy-arith.py:15: error: Unsupported operand types for + (likely involving Union)  [operator]

Your Environment

  • Mypy version used: 1.13
  • Mypy command-line flags: None
  • Mypy configuration options from None
  • Python version used: 3.13

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

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

はじめの一歩

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

調査の方向性

提供された Python 再現コードを mypy 1.13 で実行し、その結果を pyright と比較します。演算子チェックが int | A によって制約された TypeVar をどのように扱うかを追跡し、示された式のカバレッジを追加します。式が unsupported-operand エラーなしで型チェックを通過し、既存の演算子診断がそのまま維持されれば完了です。

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

評価

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

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

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