python / python/mypy

Misleading warning message when using ABCMeta instead of Protocol

Offen
#14,825 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

To Reproduce

I run this code, expecting it to type-check:

https://mypy-play.net/?mypy=latest&python=3.11&gist=d4c1190de2b786aea78cc801ee2e7829

Expected Behavior

I would expect an error perhaps like this:

main.py:42: error: Argument "key" to "max_if" has incompatible type "Callable[[str], Optional[int]]"; expected "Callable[[str], Optional[S]]" where S is a subclass of "Comparable"  [arg-type]

Actual Behavior

main.py:42: error: Argument "key" to "max_if" has incompatible type "Callable[[str], Optional[int]]"; expected "Callable[[str], None]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Note

This was very confusing. While investigating this bug, I found out that I had to define Comparable using typing.Protocol instead of ABCMeta, and then I got the code to type-check.

I guess that since mypy tries to find S which is Comparable, so that Optional[int] would match S | None, and since it recognizes that int isn't a subclass of Comparable, it is left with the None and this is what it shows in the error message. However, this is very confusing.

Your Environment

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

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

Beginnen Sie mit der verknüpften mypy-play-Reproduktion und vergleichen Sie die erzeugten Diagnosen, wenn Comparable ABCMeta gegenüber typing.Protocol verwendet. Verfolgen Sie den Pfad der Typinferenz und der Fehlerberichterstattung für das Schlüsselargument max_if. Als erledigt gilt die Aufgabe, wenn der ABCMeta-Fall eine Diagnose erzeugt, die die Inkompatibilität korrekt erklärt, anstatt Callable[[str], None] anzuzeigen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
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.