python / python/mypy

Mypy should warn when comparing lists that hold a union of incomparable types

Offen
#14,227 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Feature

As of mypy 0.991 on Python 3.11.0, mypy --strict doesn't report any problems on this code:

from typing import List, Union
a: List[Union[int, str]] = ['a']
b: List[Union[int, str]] = [1]
result = a < b

Despite mypy passing, actually running this results in TypeError: '<' not supported between instances of 'str' and 'int'. I think ideally mypy would catch this.

Pitch

While the problem was much less obvious, this affected a real project at https://github.com/certbot/certbot/issues/9481 so I think it'd be useful if mypy could help stop bugs like this from slipping through.

My knowledge of mypy and especially its internals is pretty limited, but is there a sane way to do this? Would it be possible to do something like write the annotation of list.__lt__ in the typeshed so it only accepts another list whose elements are of a type that can be compared with its own?

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

Beginne damit, das gemeldete Python 3.11-Beispiel mit mypy --strict zu reproduzieren, und bestätige den Laufzeit-TypeError. Untersuche, wie list.lt typisiert ist und ob typeshed vergleichbare Elementtypen ausdrücken kann. Als abgeschlossen gilt die Aufgabe, wenn mypy den unsicheren Vergleich meldet, ohne gültige Vergleiche von vergleichbaren Listen abzulehnen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
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.