python / python/mypy

Opt-in error for `if x:` when `x: None | int` or `None | str` etc.

Offen
#17,892 1 Kommentar 4 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

The bug function below has a bug: the else branch will execute both when x is None and when it is empty, and the latter is unexpected. The programmer was hoping "" would be handled by the if branch.

It'd be handy if Mypy could (optionally) flag this sort of mistake, to help reminder the programmer that they probably should write something like fixed, i.e. take optional values like None | str as expressing intent that "" should behave differently to None.

def bug(x: None | str):
    if x: # error: None and str
        print(f"the str value is {x}") 
    else:
        print("the value is None")

def fixed(x: None | int):
    if x is not None: # no error
        print(f"the int value is {x}") 
    else:
        print("the value is None")

This also applies to:

  • built-ins like bool, float, int, list, dict, set (etc)
  • any "truthy" types, that implement __bool__ or __len__
  • arguably, type variables that could be substituted with any of those types (e.g. def bug[T](x: None | T) called like bug(""))

Pitch

It's very easy to write if x: out of habit when handling strings, lists and any other type with falsey values. When None is involved, this can lead to unexpected behaviour, where the falsey values like [], 0, "", {} are handled like None.

Mypy is very well positioned to catch this mistake given it has full type info (and indeed linters without full type info cannot do so).

This is likely to have some false-positives, and so should be optional. It feels conceptually similar, to me, to truthy-bool.

I've sketched an incomplete implementation in https://github.com/python/mypy/pull/17893, that I can complete with agreement/guidance.

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, die unvollständige Implementierung im pull request 17893 zusammen mit den Beispielen bug und fixed des Issues zu überprüfen. Verfolge, wie mypy derzeit None | str und None | int in Wahrheitswertprüfungen eingrenzt, und ermittle anschließend das Verhalten der optionalen Diagnose sowie deren Umgang mit Built-ins, truthy-Typen und Typvariablen. Als erledigt gilt die Aufgabe, wenn die vereinbarten Fälle diagnostiziert werden, ohne dass die Prüfung standardmäßig erforderlich ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Feature
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.