it's not possible to define an 'add' that works with more than one kind of number when using number types directly
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
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
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza reproduciendo el diagnóstico de add.py con la versión de mypy indicada y revisa la discusión relacionada en el issue #3186. Investiga cómo se analizan los TypeVars acotados, las uniones numéricas y los operandos Generic; se considera terminado cuando un patrón genérico de suma numérica compatible pasa la comprobación de tipos sin los errores indicados y cuenta con cobertura de regresión.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Error
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100