How to type result based on constructor parameters?
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
I am trying to type code like this:
class A:
def __init__(self, return_tuple=False):
self.return_tuple = return_tuple
def __call__(self):
if self.return_tuple:
return (1, 2)
return 1
I have tried to make A generic and use overloads on the self parameter in several ways but none seems to work:
class A(Generic[T]):
def __init__(self, return_tuple: T = False) -> None:
self.return_tuple = return_tuple
@overload
def __call__(self: A[Literal[True]]) -> Tuple[int, int]:
pass
@overload
def __call__(self: A[Literal[False]]) -> int
pass
def __call__(self) -> Union[int, Tuple[int, int]]:
if self.return_tuple:
return (1, 2)
return 1
where T is either
T = TypeVar("T", bool)
or
T = TypeVar("T", Literal[True], Literal[False])
The first case mark errors in the definition of the TypeVar, the Generic and the optional parameter in __init__. The second one marks an error only in the optional parameter (even if it is essentially the same type). reveal_type does not have the expected result in both cases.
Am I doing something wrong or is this case just not currently taken into consideration?
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
No se nombran archivos ni pruebas. Empieza con los ejemplos de Generic[T], las sobrecargas de Literal, el parámetro del constructor y reveal_type del issue; sigue cómo mypy maneja estos patrones y determina qué comportamiento se espera. Se considera terminado establecer si este patrón de typing es compatible e identificar la limitación relevante o el cambio solicitado.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 25/100