Descriptors don't work with `TypeGuard`
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
The tool doesn't correctly interpret TypeGuard in the context of a descriptor.
To Reproduce
mypy-play.net gist
from __future__ import annotations
from typing import *
from typing_extensions import (
TypeGuard,
)
class SomeDescriptor:
# simplified: no @overload for obj=None, klass=<type ...>
def __get__(
self, obj: object, klass: Optional[Type[object]] = None
) -> TypeGuard[DerivedClass]:
return isinstance(obj, DerivedClass)
class BaseClass:
described = SomeDescriptor()
class DerivedClass(BaseClass): pass
def problem(instance: BaseClass) -> None:
if instance.described:
reveal_type(instance) # BaseClass (expected: DerivedClass)
else:
reveal_type(instance) # BaseClass (correct)
def contrast(descr: SomeDescriptor, instance: BaseClass) -> None:
if descr.__get__(instance):
reveal_type(instance) # DerivedClass (correct)
else:
reveal_type(instance) # BaseClass (correct)
Expected Behavior
In problem(), the type of instance should be narrowed when instance.described is truthy.
Actual Behavior
While mypy understands that a TypeGuard returns a bool, it doesn't narrow the type when the TypeGuard returns True.
Your Environment
- Mypy version used: 1.8.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.8, 3.12
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 collegata in mypy-play e confronta il comportamento di TypeGuard in problem() con la chiamata diretta funzionante a get in contrast(). Segui il percorso di narrowing basato sui descrittori e verifica che instance venga ristretto a DerivedClass nel ramo vero, mentre il ramo falso rimanga BaseClass.
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
- 42/100