A `class MyCallable(Protocol[T]): def __call__(self) -> T: ...` behaves differently, and worse, than a `Callable[[], T]` for the purposes of type inference.
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the example with Python 3.12 using mypy 1.12.1 and the --strict flag, comparing adapt_proto with adapt_callable. Trace why the protocol cases infer Any, and consider the issue done when the sample no longer reports the no-any-return error and both forms infer Concrete consistently.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100