python / python/mypy

Type not narrowed on `isinstance(obj, Callable)` check

Aperta
#11,071 6 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-type-narrowing
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

I received this bug report from a pyright user: https://github.com/microsoft/pyright/issues/2274. Mypy exhibits the same behavior, so I'm wondering whether it's a bug or the intended behavior.

In this code sample, mypy (and pyright) do not currently narrow the type of obj based on the isinstance(obj, Callable) conditional check.

from typing import Callable, Union

def some_func(obj: Union[Callable, int]):
    if isinstance(obj, Callable):
        reveal_type(obj) # Type of "obj" is "(*args: Unknown, **kwargs: Unknown) -> Unknown | int"
    else:
        reveal_type(obj) # Type of "obj" is "(*args: Unknown, **kwargs: Unknown) -> Unknown | int"

I'm wondering if there's a reason why mypy does not perform type narrowing in this case. Is there a type safety reason? Is callable() the preferred way to check for callables?

I've searched the issue database, and it doesn't appear to be an issue that anyone has previously reported.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il riproduttore Python con mypy e controllando i tipi rivelati per entrambi i rami. Traccia il comportamento esistente di narrowing di isinstance e Callable, inclusi eventuali test o documentazione correlati. Il lavoro è concluso quando si è stabilito se questo comportamento è intenzionale e, se si tratta di un bug, si è definito un risultato di narrowing verificato.

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
38/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.