python / python/mypy

and expression with bool() does not work with Optionals

Offen
#5,540 4 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature priority-2-low topic-strict-optional
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

For the following code, mypy reports an incompatible type error on the function f

from typing import Optional

def f(x:Optional[str]) -> bool:
  return bool(x) and g(x)

def f2(x:Optional[str]) -> bool:
  if x:
    return g(x)
  return False

def g(x: str) -> bool:
  return bool(x)
test.py:4: error: Argument 1 to "g" has incompatible type "Optional[str]"; expected "str"

however the code is equivalent to the one in f2, for which no error is raised.

  • What are the versions of mypy and Python you are using?
    Mypy: 0.620, Python: 3.6.5

  • What are the mypy flags you are using? (For example --strict-optional)

[mypy]
# This flag should be removed here and enabled per module when we have a
# considerable number of stubs for external libraries.
ignore_missing_imports = True
strict_optional = True
warn_unused_ignores = True
warn_redundant_casts = True
warn_unused_configs = True
check_untyped_defs = True

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

Führe zunächst den gemeldeten Minimal-Reproducer mit aktiviertem strict_optional aus und vergleiche die Diagnosen für f und f2. Verfolge mypy's Verarbeitung des Ausdrucks bool(x) und g(x) sowie die Eingrenzung von Optional[str]. Als abgeschlossen gilt die Aufgabe, wenn die entsprechende f-Funktion ohne den Fehler incompatible-type akzeptiert wird, während das bestehende Verhalten von f2 weiterhin gültig bleibt.

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
Klar beschrieben
Anfängerfreundlichkeit
42/100

Neue Issues direkt in Ihr Postfach

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