it's not possible to define an 'add' that works with more than one kind of number when using number types directly
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
I can't figure out how to write generic numeric code.
This is already covered to some extent by #3186, but that's about a higher-level numeric tower issue, rather than the very practical issue of code that can just work with int or float but has to keep the number type straight.
To Reproduce
from typing import TypeVar
Num = TypeVar("Num", bound=int | float)
def add(a: Num, b: Num) -> Num:
return a + b
I actually want | Decimal | Fraction in there, but that makes the problem worse.
The same issue seems to occur with Generics.
Expected Behavior
No errors.
Actual Behavior
add.py:7: error: Incompatible return value type (got "float", expected "Num")
add.py:7: error: Unsupported operand types for + (likely involving Union)
Found 2 errors in 1 file (checked 1 source file)
I understand how this would not work if I were using division, or if there were some other variance on Num but is there really some way to add an int to an int and get a float?
Your Environment
- Mypy version used: mypy 0.960 (compiled: yes)
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: Python 3.10.4 from python.org
- Operating system and version:
ProductName: macOS
ProductVersion: 12.4
BuildVersion: 21F79
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、報告された mypy のバージョンで add.py の診断を再現し、issue #3186 の関連する議論を確認してください。bound 付きの TypeVars、数値の union、Generic のオペランドがどのように解析されるかを調査します。対応している汎用的な数値加算パターンが報告されたエラーなしで型チェックを通過し、回帰テストでカバーされていれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100