python / python/mypy

MyPy fails on Union[str, int] < Union[str, int] when underlying type is known

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

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

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

説明

Bug Report

Given the following script I'm receiving several unexpected errors:

test.py:22: error: Unsupported operand types for < ("str" and "int")
test.py:22: error: Unsupported operand types for < ("int" and "str")
test.py:22: note: Both left and right operands are unions
test.py:24: error: Unsupported operand types for < ("str" and "int")
test.py:24: error: Unsupported operand types for < ("int" and "str")
test.py:24: note: Both left and right operands are unions
Found 4 errors in 1 file (checked 1 source file)

Even though the if-block and assert statement just before the comparison operator usage on a and b clearly filters out the case of mismatching types. I've only added the assert statement in the hope of telling mypy that these variables have the same type, but no luck there.

from typing import Union

def semver_prerelease_compare(lhs: str, rhs: str) -> bool:
    a: Union[str, int]
    b: Union[str, int]
    for a, b in zip(lhs.split("."), rhs.split(".")):
        try:
            a = int(a)
        except ValueError:
            pass
        try:
            b = int(b)
        except ValueError:
            pass

        if isinstance(a, int) and not isinstance(b, int):
            # Numeric identifiers sort before non-numeric ones
            return True
        if type(a) != type(b):
            return False
        if a < b:
            return True
        elif b < a:
            return False

    return len(lhs) < len(rhs)

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

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

はじめの一歩

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

調査の方向性

test.py に対して mypy を実行して報告された診断を再現し、その後、type(a) != type(b) ガードが a < b および b < a の比較に対する絞り込みにどのような影響を与えるかを追跡します。同値な型のガードによって報告された str/int エラーが発生しなくなり、その動作が回帰テストでカバーされれば完了です。

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

評価

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

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

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