Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2497,6 +2497,22 @@ def check_override(
# Use boolean variable to clarify code.
fail = False
op_method_wider_note = False
if isinstance(override, Overloaded) and isinstance(original, CallableType):
if not self.is_forward_op_method(name):
if all(is_subtype(item.ret_type, original.ret_type) for item in override.items):
# Return True to maintain backwards compatibility with existing mypy_primer
return True
if isinstance(node, OverloadedFuncDef) and node.impl and node.impl.type:
impl_type = node.impl.type
if is_subtype(impl_type, original, ignore_pos_arg_names=True):
return True
proper_impl_type = get_proper_type(impl_type)
if isinstance(proper_impl_type, CallableType):
if any(
isinstance(get_proper_type(tp), AnyType)
for tp in proper_impl_type.arg_types
):
return True
if not is_subtype(override, original, ignore_pos_arg_names=True):
fail = True
elif isinstance(override, Overloaded) and self.is_forward_op_method(name):
Expand Down
25 changes: 25 additions & 0 deletions test-data/unit/check-overloading.test
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,31 @@ class B(A):
def f(self, x: str) -> str: return ''
[out]

[case testOverloadedMethodWithNarrowerReturnTypes]
from typing import overload, Union, Optional

class A:
def view(self, x: Optional[int] = None) -> "A":
...

class B(A):
def view(self, x: Optional[int] = None) -> "B":
return B()

class C(A):
@overload # Should be allowed since B is a subtype of A
def view(self, x: int) -> B: ...
@overload # Should be allowed since C is a subtype of A
def view(self, x: None = None) -> "C": ...
def view(self, x: Optional[int] = None) -> Union[B, C]:
if x is None:
return C()
else:
return B()

reveal_type(C().view(None)) # N: Revealed type is "__main__.C"
reveal_type(C().view(5)) # N: Revealed type is "__main__.B"

[case testOverrideOverloadedMethodWithMoreSpecificArgumentTypes]
from foo import *
[file foo.pyi]
Expand Down