python / python/mypy

Wrong return type detected for @overload function

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

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

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

説明

In the scenario where a @overload function is called, mypy doesn't reliably detect the correct return value.

I'm using the following code to call PySide6 functions:

gearIcon = QIcon(str('...'))
menuSettings: QMenu = self.menuBar().addMenu('&Tools')
actionSettings = menuSettings.addAction(gearIcon, '&Settings')
actionSettings.triggered.connect(self.showSettingsDialog)

mypy assumes addAction to return None and notes the following error:

error: "None" has no attribute "triggered"

The QtWidgets.pyi includes the following type declaration:

@typing.overload
def addAction(self, arg__1:PySide6.QtGui.QAction) -> None: ...
@typing.overload
def addAction(self, arg__1:PySide6.QtGui.QIcon, arg__2:str, arg__3:object, arg__4:typing.Optional[PySide6.QtGui.QKeySequence]=...) -> None: ...
@typing.overload
def addAction(self, arg__1:str, arg__2:object, arg__3:typing.Optional[PySide6.QtGui.QKeySequence]=...) -> None: ...
@typing.overload
def addAction(self, icon:PySide6.QtGui.QIcon, text:str) -> PySide6.QtGui.QAction: ...
@typing.overload
def addAction(self, icon:PySide6.QtGui.QIcon, text:str, receiver:PySide6.QtCore.QObject, member:bytes, shortcut:PySide6.QtGui.QKeySequence=...) -> PySide6.QtGui.QAction: ...
@typing.overload
def addAction(self, text:str) -> PySide6.QtGui.QAction: ...
@typing.overload
def addAction(self, text:str, receiver:PySide6.QtCore.QObject, member:bytes, shortcut:PySide6.QtGui.QKeySequence=...) -> PySide6.QtGui.QAction: ...

The overloaded addAction function that "best" (and exactly) matches the arguments (QIcon, str) is defined to return QAction. The None returning variants don't match the argument list, so they should not be considered.

The documentation states:

When you call an overloaded function, mypy will infer the correct return type by picking the best matching variant, after taking into consideration both the argument types and arity.
...
If there are multiple equally good matching variants, mypy will select the variant that was defined first. 

Your Environment

  • Mypy version used: 0.800 (same behavior in 0.790)
  • Python version used: 3.9.1

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

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

はじめの一歩

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

調査の方向性

まず、提供された PySide6 のオーバーロードと mypy 0.800 を使って報告された呼び出しを再現し、次に mypy が QtWidgets.pyi の宣言に対してオーバーロードされた呼び出しをどのようにチェックするかを調べます。(QIcon, str) の呼び出しが None ではなく QAction を返すと推論され、その例を対象とするリグレッションテストがある状態を完了とします。

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

評価

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

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

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