Return type hint fails with multiple supplied type vars
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'm not 100% sure how to word this but mypy fails to detect the proper return type if multiple types are supplied. It works just fine if only a single type is specified.
This scenario works just fine with pyright/pylance.
To Reproduce
import typing as t
class BaseClass:
...
class Sub1(BaseClass):
...
class Sub2(BaseClass):
...
ClassType = t.TypeVar("ClassType", bound=BaseClass)
def testing_union() -> t.Union[Sub1, Sub2]:
res = sub_method(Sub1, Sub2)
reveal_type(res)
return res
def testing_single() -> Sub1:
res = sub_method(Sub1)
return res
def sub_method(*output_type: t.Type[ClassType]) -> ClassType:
return # type: ignore[return-value]
Expected Behavior
I expect mypy to work for both testing_union() and testing_single().
Actual Behavior
A return-value occurs in testing_union as it thinks the value is the bound base class. Using reveal_type we can see that mypy detects the type as BaseClass whereas pylance/pyright detects it as the expect3ed Sub1 | Sub2 type.

The output from the mypy check is
mypy-test.py:21: note: Revealed type is "mypy-test.BaseClass"
mypy-test.py:23: error: Incompatible return value type (got "BaseClass", expected "Union[Sub1, Sub2]") [return-value]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: mypy 1.0.0 (compiled: yes)
- Mypy command-line flags:
python -m mypy file.py - Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: Python 3.11.0
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
Empieza ejecutando el reproductor proporcionado con mypy 1.0.0 y compara el tipo revelado para varios argumentos de tipo frente a uno solo. Rastrea el comportamiento de inferencia de tipos para los argumentos variádicos TypeVar de sub_method; estará hecho cuando el caso de unión revele Sub1 | Sub2 y supere la comprobación de retorno declarada sin debilitar el caso de tipo único.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- compilers, devtools
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100