Skip to content

A class MyCallable(Protocol[T]): def __call__(self) -> T: ... behaves differently, and worse, than a Callable[[], T] for the purposes of type inference. #18016

@glyph

Description

@glyph

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions