it's not possible to define an 'add' that works with more than one kind of number when using number types directly
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo la diagnostica di add.py con la versione di mypy indicata e consulta la discussione correlata nell’issue #3186. Analizza come vengono valutati i TypeVars vincolati, le unioni numeriche e gli operandi Generic; il lavoro è completato quando un pattern generico di addizione numerica supportato supera il controllo dei tipi senza gli errori riportati ed è coperto da test di regressione.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100