it's not possible to define an 'add' that works with more than one kind of number when using number types directly
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, die Diagnose aus add.py mit der gemeldeten mypy-Version zu reproduzieren, und prüfe die zugehörige Diskussion in Issue #3186. Untersuche, wie begrenzte TypeVars, numerische Vereinigungen und Generic-Operanden analysiert werden; abgeschlossen ist die Aufgabe, wenn ein unterstütztes generisches numerisches Additionsmuster ohne die gemeldeten Fehler typgeprüft wird und durch Regressionstests abgedeckt ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100