python / python/mypy

Possibly-undefined: allow assertions on the lengths of sequences

Offen
#14,830 4 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

The new (disabled-by-default) possibly-undefined error code is great, and I'm using it in several of my projects. There are many hits if you enable it for typechecking mypy's own code, however. An example is this function, where mypy (correctly) points out that arg may be undefined on line 526 (arg_types might be an empty list).

https://github.com/python/mypy/blob/456dcbdd6a2f9b36249e0e7d31e521f5678a8235/mypy/suggestions.py#L509-L527

It would be nice if we could use assertions based on the truthiness of a sequence to make this error go away. E.g., it would be nice if we could silence the error here with this diff:

--- a/mypy/suggestions.py
+++ b/mypy/suggestions.py
@@ -512,6 +512,7 @@ class SuggestionEngine:
         arg_names: list[list[str | None]],
         arg_types: list[list[Type]],
     ) -> str:
+        assert arg_types
         args: list[str] = []

Mypy doesn't currently understand this idiom, however. @ilinum, how hard might this kind of thing be to implement?

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 mit dem Beispiel in mypy/suggestions.py um die Zeilen 509–527 und reproduziere die possibly-undefined-Warnung bei aktivierter Option. Verfolge den Type-Checking-Pfad für das assert arg_types-Beispiel; abgeschlossen, wenn diese Assertion korrekt feststellt, dass die Sequenz nicht leer ist, und die Warnung entfernt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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