A `class MyCallable(Protocol[T]): def __call__(self) -> T: ...` behaves differently, and worse, than a `Callable[[], T]` for the purposes of type inference.
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
See the error case reported when this is checked with mypy --strict
from typing import Callable, Protocol, TypeVar
_T = TypeVar("_T", covariant=True)
class _Adaptable(Protocol[_T]):
def __call__(self) -> _T: ...
_AdaptableCB = Callable[[], _T]
_R = TypeVar("_R")
def adapt_proto(a: _Adaptable[_R]) -> _R:
return a()
def adapt_callable(a: _AdaptableCB[_R]) -> _R:
return a()
class Concrete: ...
def factory() -> Concrete:
return Concrete()
from enum import Enum, auto
class Strategy(Enum):
callable_factory = auto()
callable_type = auto()
proto_factory = auto()
proto_type = auto()
def multi_adapt(how: Strategy) -> Concrete:
match how:
case Strategy.callable_factory:
return adapt_callable(factory)
case Strategy.callable_type:
return adapt_callable(Concrete)
case Strategy.proto_factory:
return adapt_proto(factory)
case Strategy.proto_type:
return adapt_proto(Concrete)
(A clear and concise description of what the bug is.)
To Reproduce
# Ideally, a small sample program that demonstrates the problem.
# Or even better, a reproducible playground link https://mypy-play.net/ (use the "Gist" button)
Expected Behavior
I would expect these to be identical, and the Protocol option not to degrade to Any.
Actual Behavior
main.py:44: error: Returning Any from function declared to return "Concrete" [no-any-return]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.12.1
- Mypy command-line flags:
--strict - Mypy configuration options from
mypy.ini(and other config files): None - Python version used: python 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
Riproduci l’esempio con Python 3.12 usando mypy 1.12.1 e il flag --strict, confrontando adapt_proto con adapt_callable. Analizza perché i casi di protocollo inferiscono Any e considera l’issue risolta quando l’esempio non segnala più l’errore no-any-return ed entrambe le forme inferiscono Concrete in modo coerente.
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
- 45/100