From 1772a4cc3ed5290efa95cde2c8246db183781201 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 24 Mar 2022 09:26:34 +0000 Subject: [PATCH] Let overload item have a wider return type than implementation (#12435) A wider return type can be useful if a decorator used for the overload implementation gets a more precise return type as part of a typeshed update. Closes #12434. --- mypy/checker.py | 3 ++- test-data/unit/check-overloading.test | 21 +++++++++++++++++++++ test-data/unit/fine-grained.test | 1 + 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/mypy/checker.py b/mypy/checker.py index e6c22a99c5028..a02a877a808fe 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -600,7 +600,8 @@ def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None: self.msg.overloaded_signatures_arg_specific(i + 1, defn.impl) # Is the overload alternative's return type a subtype of the implementation's? - if not is_subtype_no_promote(sig1.ret_type, impl.ret_type): + if not (is_subtype_no_promote(sig1.ret_type, impl.ret_type) or + is_subtype_no_promote(impl.ret_type, sig1.ret_type)): self.msg.overloaded_signatures_ret_specific(i + 1, defn.impl) # Here's the scoop about generators and coroutines. diff --git a/test-data/unit/check-overloading.test b/test-data/unit/check-overloading.test index 0d04074406e65..591741f3e4e8b 100644 --- a/test-data/unit/check-overloading.test +++ b/test-data/unit/check-overloading.test @@ -6328,3 +6328,24 @@ if True: def f2(x): ... if True: def f2(x): ... # E: Name "f2" already defined on line 17 + +[case testOverloadItemHasMoreGeneralReturnType] +from typing import overload + +@overload +def f() -> object: ... + +@overload +def f(x: int) -> object: ... + +def f(x: int = 0) -> int: + return x + +@overload +def g() -> object: ... + +@overload +def g(x: int) -> str: ... + +def g(x: int = 0) -> int: # E: Overloaded function implementation cannot produce return type of signature 2 + return x diff --git a/test-data/unit/fine-grained.test b/test-data/unit/fine-grained.test index ad67ff19dfd22..86872277c6e31 100644 --- a/test-data/unit/fine-grained.test +++ b/test-data/unit/fine-grained.test @@ -2084,6 +2084,7 @@ a.py:5: error: "list" expects 1 type argument, but 2 given == [case testPreviousErrorInOverloadedFunction] +# flags: --strict-optional import a [file a.py] from typing import overload