Having to add type hint 2nd time on AnyStr when assigning as instance attribute
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 reporting a potential bug/improvement in mypy.
I assign a class's instance attribute to be an argument from the __init__ signature.
I noticed that when the argument is type hinted as a AnyStr, mypy raises an error unless the instance attribute receives a second type hint.
from typing import AnyStr, Generic
class A(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case A... error: Need type annotation for 'attr'
self.attr = arg
reveal_type(arg)
# note: Revealed type is 'builtins.str*'
# note: Revealed type is 'builtins.bytes*'
reveal_type(self.attr)
# note: Revealed type is 'builtins.str'
# note: Revealed type is 'Any'
# Observation: 'builtins.bytes*' doesn't seem to propagate
class B(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case B... Success
self.attr = arg # type: AnyStr
The desirable behavior is not to have to supply a second type hint.
What's going on here? Is there some way I can not supply a second type hint?
I am invoking mypy from the command line with no flags. Here are my versions:
python==3.6.5
mypy==0.770
Aside
I am coming here from Stack Overflow, where a community member thought it was a bug: Python mypy why does class instance attribute require type hint if expression already has type hint
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 problema del fragmento de Python incluido con mypy 0.770, comparando Case A y Case B y sus tipos revelados. Rastrea la inferencia de atributos de instancia para Generic[AnyStr] y determina si la variable de tipo debería propagarse sin la anotación inline. Se considera terminado cuando Case A ya no requiere una segunda indicación de tipo y existe cobertura de regresión para el comportamiento demostrado.
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
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100