python / python/mypy

`self` annotation not checked in `__index__`?

Offen
#19,341 3 Kommentare 3 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-calls topic-protocols topic-self-types
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduziere das Beispiel im Issue mit Python 3.12 und mypy 1.16.1 und prüfe den angezeigten Typ für b * a. Verfolge, wie die self-Annotation von Array.index gegen SupportsIndex und list.mul abgeglichen wird. Als erledigt gilt, dass das Beispiel erwartungsgemäß Array[str] anzeigt und eine Regressionstestabdeckung vorhanden ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.