python / python/mypy

`self` annotation not checked in `__index__`?

Abierto
#19,341 3 comentarios 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-calls topic-protocols topic-self-types
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report

To Reproduce

from __future__ import annotations
from typing import Callable, TypeVar, Any, Protocol, Self, Any

T = TypeVar('T', covariant=True)

class Array(Protocol[T]):
    def __index__(self: Array[int], /) -> int: ...
    def dtype(self) -> T: ...
    def __rmul__(self, other: Any) -> Self: ...

def func(a: Array[str], b: list[bool]) -> None:
    result = b * a
    reveal_type(result)

https://mypy-play.net/?mypy=latest&python=3.12&gist=596075fa56c1bd714ec44b224f5ed97c

Expected Behavior

t.py:13: note: Revealed type is "Array[str]"

(which is what Pyright does)

This is because list.__mul__ is defined as

https://github.com/python/typeshed/blob/7aad2554355b55e70e4137fadf48f294ee79efaf/stdlib/builtins.pyi#L1124

    def __mul__(self, value: SupportsIndex, /) -> list[_T]: ...

and SupportsIndex checks for __index__(self) -> int, and if value is Array[str], then Array.__index__ is not matched

Actual Behavior

t.py:13: note: Revealed type is "builtins.list[builtins.bool]"

Your Environment

  • Mypy version used: 1.16.1
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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

Reproduce el ejemplo del issue con Python 3.12 y mypy 1.16.1, comprobando el tipo revelado para b * a. Rastrea cómo se compara la anotación self de Array.index con SupportsIndex y list.mul. Se considera completado cuando el ejemplo revela Array[str] como se espera y existe cobertura 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
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.