Generic class with constrained type vars
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Merge medio
- 1 d 18 h
- PR fusionados (30 d)
- 54
Descripción
On Python 3.7.0 and mypy 0.620, I'm getting some error messages I don't understand. The Mypy documentation and PEP 484 didn't clear it up for me. Maybe it's a bug in Mypy. Maybe I don't understand type erasure. In case it's the former, here's a minimal example. In case it's the latter, please help.
In the following examples, the fact that m does not return is not critical. In the real code that gave me these errors, m is an abstract method, which also doesn't change anything important.
Put the following examples in mypy-test.py to get the corresponding output from running mypyt mypy-test.py. The first and the last examples are the ones that are baffling me.
classmethod with constrained type variable
from typing import TypeVar, Generic
T = TypeVar('T', int, str)
class K(Generic[T]):
@classmethod
def m(cls) -> T:
raise NotImplementedError
Mypy output:
mypy-test.py:5: error: The erased type of self 'def [T in (builtins.int, builtins.str)] () -> mypy-test.K[builtins.int*]' is not a supertype of its class 'Type[mypy-test.K[T`1]]'
mypy-test.py:5: error: The erased type of self 'def [T in (builtins.int, builtins.str)] () -> mypy-test.K[builtins.str*]' is not a supertype of its class 'Type[mypy-test.K[T`1]]'
classmethod with generic self
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T', int, str)
class K(Generic[T]):
@classmethod
def m(cls: S) -> T:
raise NotImplementedError
produces no error.
classmethod with unconstrained type variable
from typing import TypeVar, Generic
T = TypeVar('T')
class K(Generic[T]):
@classmethod
def m(cls) -> T:
raise NotImplementedError
produces no error.
instance method with constrained type
from typing import TypeVar, Generic
T = TypeVar('T', int, str)
class K(Generic[T]):
def __init__(self, t: T) -> None:
self.t = t
produces
mypy-test.py:5: error: Need type annotation for 't'
instance method with unconstrained type
from typing import TypeVar, Generic
T = TypeVar('T')
class K(Generic[T]):
def __init__(self, t: T) -> None:
self.t = t
produces no error.
instance method with constrained type and inheritance
from typing import TypeVar, Generic
T = TypeVar('T', int, str)
class K(Generic[T]):
def __init__(self, t: T) -> None:
self.t: T = t
class L(K[T]):
def __init__(self, t: T) -> None:
self.u = 1
super().__init__(t=t)
produces
mypy-test.py:10: error: Argument "t" to "__init__" of "K" has incompatible type "int"; expected "T"
mypy-test.py:10: error: Argument "t" to "__init__" of "K" has incompatible type "str"; expected "T"
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
Reproduce los ejemplos de mypy-test.py con Python 3.7.0 y mypy 0.620, comenzando por los métodos de clase genéricos restringidos y no restringidos. Compara los diagnósticos para los métodos de clase, los atributos de instancia y los constructores heredados; después, determina el comportamiento previsto antes de decidir si se necesitan cambios en la implementación o pruebas 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
- Necesita aclaración
- Aptitud para principiantes
- 25/100