python / python/mypy

__iadd__ is not applied for += when TypeVars with bound are used.

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

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

bug topic-protocols topic-type-variables
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Bug Report

Using += with TypeVar bound on Protocol implementing __iadd__ causes error:

Unsupported left operand type for + ("U")

To Reproduce

Define Protocol and generic method as shown below.

# main.py


from __future__ import annotations
from typing import Generic, Protocol, TypeVar     


T = TypeVar("T")
U = TypeVar("U", bound=SupportsIAdd)


class SupportsIAdd(Protocol):
    def __iadd__(self: T, other: T) -> T: ...        


class AddingAccumulatorParam(Generic[U]):
    def addInPlace(self, value1: U, value2: U) -> U:
        value1 += value2  # Fails
        return value1

Expected Behavior

It should pass mypy checks, as U is bound on SupportIAdd which in turn provides __iadd__ that can be used for +=.

Actual Behavior

The snippet shown above fails with:

main.py:17: error: Unsupported left operand type for + ("U")
Found 1 error in 1 file (checked 1 source file)

Replacing __iadd__ with __add__ makes mypy happy (so clearly mypy can infer required operation and fall back with +).

# main.py

from __future__ import annotations
from typing import Generic, Protocol, TypeVar     


T = TypeVar("T")
U = TypeVar("U", bound=SupportsIAdd)


class SupportsIAdd(Protocol):
    def __add__(self: T, other: T) -> T: ... 


class AddingAccumulatorParam(Generic[U]):
    def addInPlace(self, value1: U, value2: U) -> U:
        value1 += value2  # Passes just fine
        return value1

On Further investigation, it seems like the issue might be related to bound TypeVar ‒ if I replace Protocol

class SupportsIAdd(Protocol):

with plain class

class SupportsIAdd:

the problem still exists, but if I tweak the signature of the method that uses it, to take exact class

# main.py

from __future__ import annotations
from typing import Any, TypeVar              


class SupportsIAdd:          
    def __iadd__(self, other: Any) -> SupportsIAdd: ...         


class AddingAccumulatorParam:            
    def addInPlace(self, value1: SupportsIAdd, value2: SupportsIAdd) -> SupportsIAdd:            
        value1 += value2
        return value1

it passes.

Finally (credit goes to @hauntsaninja) applying __iadd__ directly

class AddingAccumulatorParam(Generic[U]):
    def addInPlace(self, value1: U, value2: U) -> U:
        return reveal_type(value1.__iadd__(value2))

yields expected result

main.py:17: note: Revealed type is "U`1"

Your Environment

  • Mypy version used: Both 0.910 and dev.
  • Mypy command-line flags: Default flags.
  • Mypy configuration options from mypy.ini (and other config files): No additional config used.

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

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

はじめの一歩

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

調査の方向性

まず、デフォルトのフラグを使って mypy で main.py の例を再現し、+= と iadd および add の直接呼び出しを比較します。Protocol iadd を持つ bound TypeVar のリグレッションカバレッジを追加します。例が unsupported-left-operand エラーなしで通れば完了です。

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

評価

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

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

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