python / python/mypy

__r<magic>__ methods for reflected (swapped) operands doesnt duck type int to float

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

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

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

説明

🐛 Bug Report

It seems like ints are not compatible with floats when used in the __r<magic>__ methods for reflected (swapped) operands like __radd__ the same was as in normal operands if the int/float is used as a type parameter in a generic type.

As a workaround it works if I specify a union type with the int case as well, but would be nice to not have to do that since its not needed otherwise.

To Reproduce

code.py:

from typing import List

class Vec:
    def __add__(self, other: List[float]) -> None:
        pass

    def __radd__(self, other: List[float]) -> None:
        pass

r1 = Vec() + [1]
r2 = [1] + Vec()  # error line
r3 = [1.0] + Vec()

Type checking the above code with python -m mypy code.py

Expected Behavior

I expect the r2 case to work as well

Actual Behavior

I get this error message for the r2 line: error: Unsupported operand types for + ("List[int]" and "Vec")

Your Environment

  • Mypy version used: 0.782
  • Mypy configuration options from mypy.ini (and other config files): No special config
  • Python version used: CPython 3.8.4, 32 bit.
  • Operating system and version: Windows 10

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

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

はじめの一歩

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

調査の方向性

issue の code.py にある再現コードから始め、報告されたケースを使って python -m mypy code.py を実行します。List[int]List[float] を比較したときに、オペランドのチェックが __add__ と反射された __radd__ をどのように扱うかを追跡します。完了の条件は、既存のケースが引き続き正しく、r2 ケースが union の回避策を必要とせずに型チェックを通ることです。

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

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
45/100

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

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