python / python/mypy

Subclass attribute type narrowing on assignment

Abierto
#14,760 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

documentation
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Documentation

Consider this code snippet:

from typing import Iterable


class A:
    attr1: Iterable[str]  # narrows to different type, specific number of elements.
    attr2: tuple[str, ...]  # narrows to specific number of elements



class B(A):
    attr1 = "a", "b"
    attr2 = "a", "b", "c"


reveal_type(B.attr1)
reveal_type(B.attr2)

With this, mypy will tell us that Revealed type is "Tuple[builtins.str, builtins.str]" and Revealed type is "Tuple[builtins.str, builtins.str, builtins.str]" for attr1 and attr2 respectively. I can't find this behaviour documented, neither in PEP484, nor the Python typing docs, nor mypy docs. I don't even know where this should be documented best. But for what it's worth, I asked pylance, which says Type of "B.attr1" is "tuple[str, ...]" and Type of "B.attr2" is "tuple[str, ...]". Which tells me that the intended behaviour isn't clear for other people, too.

Note: I'm aware that this may be a bug report instead. But I rather err on the side of this not being clearly specified yet than being incorrectly implemented.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza leyendo PEP 484, la documentación de typing de Python y la documentación de mypy sobre las asignaciones de subclases mostradas. Compara los tipos revelados por mypy con los informes de Pylance y, después, documenta el comportamiento previsto o aclara si la discrepancia debe tratarse como un error.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
documentation
Tipo de issue
Documentación
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.