python / python/mypy

reassignment of a `TypeAliasType` should not be evaluated as type expression

Offen
#20,308 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Unsurpringly, reassigning some generic TypeAliasType named A as B = A is not the same as subscripting it as B = A[Any]:

>>> type A[T] = T | str
>>> B = A
>>> type(A)
<class 'typing.TypeAliasType'>
>>> type(B)
<class 'typing.TypeAliasType'>
>>> A is B
True

Mypy's behavior (on master and 1.18.2) contradicts this:

type A[T] = T | T   # ✔️ true negative
B = A               # ❌ false positive: Missing type parameters for generic type "A"  [type-arg]

reveal_type(A)      # ✔️ mypy: "typing.TypeAliasType",      runtime: "typing.TypeAliasType"
reveal_type(B)      # ❌ mypy: "types.UnionType[Any, Any]", runtime: "typing.TypeAliasType"

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=962d28cd59eff168c9cd2057e9f18f88

The error at line 2 is only reported in strict mode, so if you don't use that, I can imagine that it can be rather difficult to debug.

I realize that mypy interprets B = A as if it's B: TypeAlias = A, and it's not like there's nothing to be said for that. But I think that it's rather unlikely that a someone using the type keyword would expect that omitting it would result in the exact same behavior.
For _: TypeAlias that's a different story, and is currently working fine IMO; so I'm purely talking about TypeAliasType here. And given the differences in runtime semantics between the two, I think it's fair to treat them differently.


p.s. congratz with the 20k stars!

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

Reproduziere das gemeldete Verhalten mit dem verlinkten mypy-play-Beispiel und vergleiche B = A mit B = A[Any], einschließlich der Diagnosen im Strict-Modus und der aufgelösten Typen. Verfolge, wie Zuweisungen mit generischem TypeAliasType interpretiert werden, und füge gezielte Tests hinzu, die zeigen, dass eine erneute Zuweisung das Alias-Objekt erhält und keinen Fehler wegen fehlender Typparameter erzeugt.

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
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

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