MyPy fails on Union[str, int] < Union[str, int] when underlying type is known
オープン
まだ誰も着手していません。
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)
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
test.py に対して mypy を実行して報告された診断を再現し、その後、type(a) != type(b) ガードが a < b および b < a の比較に対する絞り込みにどのような影響を与えるかを追跡します。同値な型のガードによって報告された str/int エラーが発生しなくなり、その動作が回帰テストでカバーされれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 42/100