Unable to stubify Enum so it can be used with Literals, without using type ignore
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
Extending the example for #3434 I want to define an enum Flag, combine some of the members, and then also reference those members as a TypeAlias in a stub file.
class Color1(Flag):
RED = auto()
BLUE = auto()
GREEN = auto()
WHITE = RED | BLUE | GREEN # <-- This line works at runtime but not in a stub (see the gist)
# Invalid type: try using Literal[Color1.RED] instead
Favorites: TypeAlias = Literal[Color3.RED | Color3.BLUE]
(A clear and concise description of what the bug is.)
To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=d270d7541c61b2aea87e99c9afc77534
Expected Behavior
I expect mypy to suggest working code, or to accept the | operator for Flag members.
Actual Behavior
See the gist, but depending on how I write the stub I get these errors for the member definition
# foo.pyi:9: error: Invalid type: try using Literal[Color1.RED] instead? [valid-type]
# foo.pyi:9: error: Invalid type: try using Literal[Color1.BLUE] instead? [valid-type]
# foo.pyi:9: error: Invalid type: try using Literal[Color1.GREEN] instead? [valid-type]
or these for the TypeAlias
# foo.pyi:12: error: Parameter 1 of Literal[...] cannot be of type "Any" [valid-type]
Your Environment
- Mypy version used: 1.5.1
- Mypy command-line flags:
--strict - Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.10.13
I was curious what stubgen came up with:
from _typeshed import Incomplete
from enum import Flag
from typing import TypeAlias
class Color(Flag):
RED: Incomplete
BLUE: Incomplete
GREEN: Incomplete
WHITE: Incomplete
Favorites: TypeAlias
but that loses information about the Literal Favorite Colors.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con la riproduzione in mypy-play e gli esempi foo.pyi nel report, concentrandoti sulle definizioni dei membri di Flag e sul Literal TypeAlias. Confronta gli errori valid-type e Any segnalati con la gestione prevista dei membri combinati di Flag; il lavoro è completato quando lo stub previsto conserva le informazioni sul colore literal senza richiedere type ignores.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100