From 2f1e8c6bebe7652ce1401bd4a2f52e22088dd8e8 Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Sun, 3 Nov 2024 18:06:51 -0800 Subject: [PATCH] Fix subtyping between Instance and Overloaded Fixes #18101 --- mypy/subtypes.py | 4 ++-- test-data/unit/check-protocols.test | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/mypy/subtypes.py b/mypy/subtypes.py index a63db93fd9cb8..11f3421331a57 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -625,8 +625,8 @@ def visit_instance(self, left: Instance) -> bool: return is_named_instance(item, "builtins.object") if isinstance(right, LiteralType) and left.last_known_value is not None: return self._is_subtype(left.last_known_value, right) - if isinstance(right, CallableType): - # Special case: Instance can be a subtype of Callable. + if isinstance(right, FunctionLike): + # Special case: Instance can be a subtype of Callable / Overloaded. call = find_member("__call__", left, left, is_operator=True) if call: return self._is_subtype(call, right) diff --git a/test-data/unit/check-protocols.test b/test-data/unit/check-protocols.test index 5ed2351e33e6c..0367be3dde652 100644 --- a/test-data/unit/check-protocols.test +++ b/test-data/unit/check-protocols.test @@ -4215,3 +4215,24 @@ def g4(a: Input[bytes], b: Output[str]) -> None: f(a, b) # E: Cannot infer type argument 1 of "f" [builtins fixtures/tuple.pyi] + +[case testOverloadProtocolSubtyping] +from typing import Protocol, Self, overload + +class NumpyFloat: + __add__: "FloatOP" + +class FloatOP(Protocol): + @overload + def __call__(self, other: float) -> NumpyFloat: ... + @overload + def __call__(self, other: NumpyFloat) -> NumpyFloat: ... + +class SupportsAdd(Protocol): + @overload + def __add__(self, other: float) -> Self: ... + @overload + def __add__(self, other: NumpyFloat) -> Self: ... + +x: SupportsAdd = NumpyFloat() +[builtins fixtures/tuple.pyi]