python / python/mypy

Constant vs variable as index for none-checking List[Optional[...]]

Offen
#12,413 11 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Can you explain to me why there is this difference between using a constant and a variable as index for none-checking here?

from typing import List, Optional

my_list: List[Optional[float]] = []

if my_list[0] is not None:
    result_1: float = my_list[0]        # no error
    result_2: float = my_list[1]        # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")

id_0 = 0
if my_list[id_0] is not None:
    result_3: float = my_list[id_0]     # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")


for i in range(10):
    if my_list[i] is not None:
        a: float = my_list[i]           # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
  • Mypy version used: 0.800 0.941
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: python3.6
  • Operating system and version: Ubuntu 18.04 in WSL2 (Windows 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

Das Issue nennt keine Repository-Dateien oder Tests. Reproduziere die Beispiele mit mypy 0.941 und verfolge anschließend das Type-Narrowing-Verhalten für indizierte List[Optional[float]]-Ausdrücke. Als erledigt gilt die Aufgabe, wenn das unterschiedliche Verhalten bei Konstanten, Variablen und Schleifenindizes erklärt ist und, falls es als Bug bestätigt wird, durch einen geeigneten Regressionstest abgedeckt 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.