Type-narrowing based on instance type
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
I would like to do a form of type narrowing based on the instance type. Minimal example in the script below.
mypy tells me that my script is not a valid pattern though. Is this true, or is it a bug?
To Reproduce
from typing import overload, Protocol, Self
class HasOverride(Protocol):
override: bool
class A():
@overload
def fake_method(self: HasOverride) -> "A":
...
@overload
def fake_method(self) -> Self:
...
def fake_method(self) -> Self | "A":
if hasattr(self, 'override'):
return A()
return self
class B(A): # fake_method should return B
pass
class C(A): # fake_method should return A
override = True
Expected Behavior
mypy 1.16.0 raises the following error:
error: Overloaded function implementation cannot satisfy signature 1 due to inconsistencies in how they use type variables [misc]
pyright 1.1.403 does not raise an error.
It seems reasonable to me to allow this pattern, which is why I am opening this as a bug report.
If this is in fact desired behaviour, I would be very grateful for an explanation and, if possible, a suggested alternative pattern (I'm a bit desperate!).
Actual Behavior
Your Environment
- Mypy version used: 1.16.0 (but have also repeated on 1.17.1)
- Mypy command-line flags: just
mypy(from a clean environment I pip installedmypyand then ran `mypy on the script above) - Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.11.13
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 dallo script Python minimo nel report ed eseguilo con mypy 1.16.0 o 1.17.1 usando il comando predefinito, quindi confronta il risultato con pyright 1.1.403. Traccia il controllo di coerenza dell’implementazione di overload e determina se il pattern segnalato debba essere accettato; il lavoro è completo quando il comportamento è risolto e questo esempio è coperto.
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
- 38/100