python / python/mypy

Weird error message for incompatible override when using a `TypeVar` for `self`

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

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

bug topic-error-reporting topic-inheritance topic-self-types topic-usability
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

Minimal repro:

from typing import TypeVar

Self = TypeVar("Self")

class Flag:
    def __or__(self: Self, other: Self) -> Self: ...
    __ror__ = __or__

class IntFlag(int, Flag):
    def __or__(self: Self, other: int) -> Self: ...
    def __ror__(self: Self, other: int) -> Self: ...

mypy output:

main.py:11: error: Signature of "__ror__" incompatible with supertype "Flag"
main.py:11: note:      Superclass:
main.py:11: note:          def [Self] __or__(self, Self, Self) -> Self
main.py:11: note:      Subclass:
main.py:11: note:          def __ror__(self, int) -> IntFlag

Mypy playground link here: https://mypy-play.net/?mypy=latest&python=3.10&gist=26b60881cd02e608bb9e555db4c3f627

Expected Behavior

I'm not sure an error is even appropriate here: no incompatible override is reported for __or__.

Even if an error is appropriate here, however, the error message is weird and garbled. According to the error message, mypy seems to think that __ror__ in the superclass expects three arguments (it only expects two). It also seems to think the method in the subclass will return IntFlag (not necessarily true; the return type will be whatever self is, and self could be any subtype of IntFlag).

The function that creates this error message is here: https://github.com/python/mypy/blob/9b4bce9065cbef6185fbc77f2849b63dc9e5e293/mypy/messages.py#L824

Mypy version used

  • 0.950.
  • This doesn't seem to be a recent regression: I can reproduce as far back as 0.920, which is the earliest mypy version that has the verbose error messages.
  • I've also reproduced the bug on mypy master.

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

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

はじめの一歩

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

調査の方向性

最小限の Python 再現例から始め、824 行付近の mypy/messages.py にある診断の構築を調べてください。報告されたスーパークラスとサブクラスのシグネチャを TypeVar ベースの self 型と比較し、そのうえで override を受け入れるべきか、またはそのメッセージをどのように表示すべきかを判断してください。動作が修正され、再現例が回帰テストでカバーされれば完了です。

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

評価

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

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

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