Skip to content

Commit

Permalink
Fix incompatible overrides of overloaded methods in concrete subclasses
Browse files Browse the repository at this point in the history
Fixes #14002
  • Loading branch information
hauntsaninja committed Nov 5, 2022
1 parent 428b172 commit d986d87
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
12 changes: 12 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1868,6 +1868,18 @@ def check_method_override_for_base_with_name(
original_class_or_static = False # a variable can't be class or static

if isinstance(original_type, FunctionLike):
active_self_type = self.scope.active_self_type()
if isinstance(original_type, Overloaded) and active_self_type:
# If we have an overload, filter to overloads that match the self type.
# This avoids false positives for concrete subclasses of generic classes,
# see testSelfTypeOverrideCompatibility for an example.
# It's possible we might want to do this as part of bind_and_map_method
filtered_items = [
item for item in original_type.items
if not item.arg_types or is_subtype(active_self_type, item.arg_types[0])
]
if filtered_items:
original_type = Overloaded(filtered_items)
original_type = self.bind_and_map_method(base_attr, original_type, defn.info, base)
if original_node and is_property(original_node):
original_type = get_property_type(original_type)
Expand Down
51 changes: 51 additions & 0 deletions test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,57 @@ reveal_type(cast(A, C()).copy()) # N: Revealed type is "__main__.A"

[builtins fixtures/bool.pyi]

[case testSelfTypeOverrideCompatibility]
from typing import overload, TypeVar, Generic

T = TypeVar("T", str, int)

class A(Generic[T]):
@overload
def f(self: A[int]) -> int: ...
@overload
def f(self: A[str]) -> str: ...
def f(self): ...

class B(A[T]):
@overload
def f(self: A[int]) -> int: ...
@overload
def f(self: A[str]) -> str: ...
def f(self): ...

class C(A[int]):
def f(self) -> int: ...

class D(A[str]):
def f(self) -> int: ... # E: Signature of "f" incompatible with supertype "A" \
# N: Superclass: \
# N: @overload \
# N: def f(self) -> str \
# N: Subclass: \
# N: def f(self) -> int

class E(A[T]):
def f(self) -> int: ... # E: Signature of "f" incompatible with supertype "A" \
# N: Superclass: \
# N: @overload \
# N: def f(self) -> int \
# N: @overload \
# N: def f(self) -> str \
# N: Subclass: \
# N: def f(self) -> int


class F(A[bytes]): # E: Value of type variable "T" of "A" cannot be "bytes"
def f(self) -> bytes: ... # E: Signature of "f" incompatible with supertype "A" \
# N: Superclass: \
# N: @overload \
# N: def f(self) -> int \
# N: @overload \
# N: def f(self) -> str \
# N: Subclass: \
# N: def f(self) -> bytes

[case testSelfTypeSuper]
from typing import TypeVar, cast

Expand Down

0 comments on commit d986d87

Please sign in to comment.