python / python/mypy

Mypy doesn't seem to use types from @overload-ed __sub__

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

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

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

説明

Bug Report

The __sub__ method on the Arrow class from the arrow package has several @overloads:

@overload
def __sub__(self, other: Union[timedelta, relativedelta]) -> "Arrow":
    pass  # pragma: no cover

@overload
def __sub__(self, other: Union[dt_datetime, "Arrow"]) -> timedelta:
    pass  # pragma: no cover

def __sub__(self, other: Any) -> Union[timedelta, "Arrow"]:

    if isinstance(other, (timedelta, relativedelta)):
        return self.fromdatetime(self._datetime - other, self._datetime.tzinfo)

    elif isinstance(other, dt_datetime):
        return self._datetime - other

    elif isinstance(other, Arrow):
        return self._datetime - other._datetime

    return NotImplemented

In particular, one Arrow object minus another Arrow object will always yield a timedelta. However, it seems mypy does not see this, and mistakes the type for Arrow.

To Reproduce

I discovered the issue when finding the time diff between two arrow timestamps:

import arrow

a1 = arrow.get()
a2 = arrow.get()

diff = a2 - a1
print(diff.total_seconds())

Which, when run with mypy yields:

$ mypy test.py
test.py:6: error: "int" not callable
Found 1 error in 1 file (checked 1 source file)

Setting the type explicitly reviles that mypy thinks the type is Arrow, and not timedelta:

from datetime import timedelta
import arrow

a1 = arrow.get()
a2 = arrow.get()

diff: timedelta = a2 - a1
print(diff.total_seconds())

Running mypy:

$ mypy test.py
test.py:7: error: Incompatible types in assignment (expression has type "Arrow", variable has type "timedelta")
Found 1 error in 1 file (checked 1 source file)

Expected Behavior

The second @overload on Arrow's __sub__ method specifies that the diff of two Arrow objects is a timedelta. There should be no type error assigning that to a timedelta variable.

Actual Behavior

Mypy mistakenly thinks the diff is Arrow, which creates a false positive.

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.9.6
  • Operating system and version: Mac OS 11.6 (Big Sur)

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

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

はじめの一歩

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

調査の方向性

まず、Python スニペットと記載された mypy 0.910 環境を使って、報告された推論エラーを再現します。arrow/arrow.py のオーバーロード宣言を読み、その後、オーバーロードされた sub 呼び出しを mypy がどのように処理するかを追跡します。Arrow から Arrow を引いた結果が timedelta として推論され、示されている代入と total_seconds() の呼び出しが型チェックを通れば完了です。

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

評価

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

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

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