Narrowing enums causes `.value` to be typed as `Any`
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
Apologies if this has already been reported, but I couldn't find an existing issue for it.
The issue I'm seeing is related to accessing the .value of an Enum after "narrowing" it with the is operator. It seems like the narrowing (to Union[Literal[...]]) works as expected, but then it fails to realize that the .value of all the variants have the same type (and so falls back to Any).
This only affects runs with --warn-return-any enabled:
$ mypy --config-file /dev/null --warn-return-any enum_narrowing.py
To Reproduce
It's probably easiest to see in this example:
import enum
from typing import Tuple
RGB = Tuple[int, int, int]
class Color(enum.Enum):
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def red(self) -> int:
if self is Color.WHITE:
return 255
return self.value[0] # error: Returning Any from function declared to return "int"
(playground URL: https://mypy-play.net/?mypy=latest&python=3.8&flags=warn-return-any&gist=b2a6df92fb37717e5c9d7542b6e88fec)
Expected Behavior
This should deduce that self.value has type RGB and succeed.
Actual Behavior
If I add some reveal_type(self) and reveal_type(self.value)s before/after the narrowing, I get this output:
enum_narrowing.py:11: note: Revealed type is "enum_narrowing.Color"
enum_narrowing.py:12: note: Revealed type is "Tuple[Literal[255]?, Literal[255]?, Literal[255]?]"
enum_narrowing.py:15: note: Revealed type is "Literal[enum_narrowing.Color.BLACK]"
enum_narrowing.py:16: note: Revealed type is "Any"
Your Environment
$ python --version
Python 3.8.0
$ mypy --version
mypy 0.991 (compiled: yes)
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 eseguendo il comando mypy fornito su enum_narrowing.py e confronta i tipi rivelati prima e dopo il restringimento con is. Segui il restringimento dei membri dell’enum e la gestione del tipo .value; la correzione è completa quando self.value[0] viene inferito come int e l’esempio passa con --warn-return-any.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 48/100