Checking elements of a `list[str | None]` after discarding the possibility of `None`
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
str_none: list[str | None]
only_str: list[str]
for i in range(len(sequence)):
if sequence[i] is not None:
only_str.append(sequence[i]) # Here mypy raises an error due to "incompatible types"
The code above raises the following error Argument 1 to "append" of "list" has incompatible type "str | None"; expected "str".
I've found the following verbose workaround but to my taste its :
str_none: list[str | None]
only_str: list[str]
for i in range(len(sequence)):
element = sequence[i]
if element is not None:
only_str.append(element)
To Reproduce
See code example above.
Expected Behavior
I'm expecting mypy to be able to predict future annotations of sequences with multiple types possible after discarding a specific type in a condition.
Actual Behavior
All is included above.
Your Environment
- Mypy version used: 1.5.1
- Mypy command-line flags: both
--strictand none - Mypy configuration options from
mypy.ini(and other config files): - Python version used: 3.11.5
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Führe zunächst den minimalen Reproducer aus dem Issue mit mypy 1.5.1 aus und verfolge anschließend das Verhalten der Typ-Eingrenzung beim indizierten Zugriff auf Sequenzen. Fertig ist die Arbeit, wenn das Beispiel das eingegrenzte Element ohne den ausführlichen Workaround mit einer lokalen Variable akzeptiert und ein Regressionstest den gemeldeten Fall abdeckt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 3/5
- Geschätzter Aufwand
- 1-2 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 42/100