Type narrowing of `Any` with `is` can widen type of variable for enum member to `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
Possibly related to #21364 and other union narrowing, although this occurs without a union.
When the following pattern is used to define a sentinel, strange "narrowing" behavior can occur:
class SentinelType(enum.Enum):
SENTINEL = enum.auto()
SENTINEL: SentinelType = SentinelType.SENTINEL
If x: Any is narrowed by the comparison x is SENTINEL, mypy will start to treat SENTINEL as having type Any.
This does not happen if the namespaced enum member, SentinelType.SENTINEL is used. Only when a separate variable is used.
To Reproduce
https://mypy-play.net/?gist=174c92c83f84f44b2e8fefdcf5a0cd9b
import enum
import typing as t
class SentinelType(enum.Enum):
SENTINEL = enum.auto()
SENTINEL: SentinelType = SentinelType.SENTINEL
x: t.Any = None
if x is SENTINEL:
t.reveal_type(SENTINEL)
Expected Behavior
The type of SENTINEL should not be altered.
Actual Behavior
SENTINEL's revealed type is Any.
Your Environment
- Mypy version used: 2.0, 2.1
- Python version used: 3.10, 3.12, 3.14
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 il reproducer mypy-play collegato ed eseguilo con il codice Python mostrato; controlla l'output di reveal_type per SENTINEL all'interno del ramo is. Traccia il percorso del restringimento dei tipi per i confronti che coinvolgono Any e un membro di enum assegnato separatamente; il lavoro è completato quando SENTINEL mantiene il SentinelType dichiarato invece di diventare Any.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers, devtools
- Tipo di issue
- Bug
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Stato di attività
- Tranquilla
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 68/100