python / python/mypy

mypy accepts invalid PEP 604 syntax with forward reference

Offen
#14,397 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature topic-pep-604 topic-runtime-semantics
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

PEP 604 introduced the | syntax, however it's not entirely equivalent to the Union syntax. Forward references with | are not supported and result in TypeErrors TypeError: unsupported operand type(s) for |: 'type' and 'str'. Mypy doesn't warn the user about this and accepts | with forward references.

To Reproduce

T = list[int | "T"]

Playground

Expected Behavior

Some kind of error telling me that this syntax is not supported.

Actual Behavior

No errors reported.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict or no flags, doesn't matter
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11

I originally raised this as a discussion in pyright repo. And since then pyright has implemented https://github.com/microsoft/pyright/commit/6eb846709f4fec0180593f3e89f1dd5b20f41956 to detect this incorrect usage of | (available in release 1.1.285). I have to admit that documentation on this is a bit murky as I was expecting | to be equivalent to Union and I wasn't the only one, see https://github.com/python/cpython/issues/90015. From what I can gather in this CPython issue runtime won't be changed to make this syntax valid and docs should be changed instead (but neither happened yet).

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, mypy auf dem bereitgestellten Reproducer T = list[int | "T"] auszuführen, und verfolge, wie Forward References in PEP 604-Unions analysiert werden. Füge für dieses Beispiel einen Regressionstest hinzu und stelle sicher, dass mypy meldet, dass die Syntax nicht unterstützt wird, während die Verarbeitung gültiger Unions erhalten bleibt.

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

Neue Issues direkt in Ihr Postfach

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