python / python/mypy

exc_info inside an except clause will always return not None

Offen
#8,819 3 Kommentare 5 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

When calling sys.exc_info from inside an except block, the returned variables will never be None, as defined by the standard library.

However, when trying to use one of the returned variables, mypy throws an error as the type is set as Optional[Type[BaseException]].

Here's the output:

> mypy test.py
test.py:8: error: Item "None" of "Optional[Type[BaseException]]" has no attribute "__name__"
Found 1 error in 1 file (checked 1 source file)

Here's the code I'm using to test:

import sys

# This causes the error
try:
    raise Exception
except Exception:
    ex, val, _ = sys.exc_info()
    print(f"Failed: {ex.__name__}: {val}")  # Line 8

# This does not
try:
    raise Exception
except Exception:
    ex, val, _ = sys.exc_info()
    if ex is not None:  # Pointless comparison
        print(f"Failed: {ex.__name__}: {val}")

I'm not sure if this is a bug or a missing feature?

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 der test.py-Reproduktion und vergleiche den von mypy abgeleiteten Typ für sys.exc_info() innerhalb des except-Blocks mit dem im Issue beschriebenen Verhalten der Standardbibliothek. Bestätige das erwartete Ergebnis, indem du mypy für das Beispiel ausführst: Der Zugriff auf ex.name sollte keine sinnlose None-Prüfung erfordern.

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
35/100

Neue Issues direkt in Ihr Postfach

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