python / python/mypy

Strange error when calling len() on a class without __len__ and then using the result for division

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

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

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

説明

Bug Report

Consider this code:

class A: ...

b = 3.0
c = b / len(A())
reveal_type(c)

mypy gives this result:

division.py:4: error: Unsupported operand types for / ("float" and "int")
division.py:4: error: Argument 1 to "len" has incompatible type "A"; expected "Sized"
division.py:5: note: Revealed type is "Any"
Found 2 errors in 1 file (checked 1 source file)

The second error is expected, but the first one (“Unsupported operand types for / ("float" and "int").”) is very confusing, because clearly division is defined for float and int.

If A has __len__, everything is fine:

class A:
    def __len__(self) -> int: return 0

b = 3.0
c = b / len(A())
reveal_type(c)

mypy output:

division.py:6: note: Revealed type is "builtins.float"
Success: no issues found in 1 source file

Your Environment

  • Mypy version used: 0.960
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10
  • Operating system and version: Ubuntu 22.04

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

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

はじめの一歩

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

調査の方向性

len()、除算、reveal_type を使用する報告済みの Python スニペットから始め、指定された mypy のバージョンを使い、フラグなしで再現します。型チェッカーが len() の無効な引数と、それによって生じる除算をどのように処理するかを追跡し、その後、除算に対する診断が誤解を招くものではない一方で、無効な len() 呼び出しは引き続き報告されることを示す、対象を絞ったカバレッジを追加します。

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

評価

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

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

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