Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow union-with-callable attributes to be overridden by methods #18018

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2154,6 +2154,11 @@ def check_method_override_for_base_with_name(
override_class_or_static,
context,
)
elif isinstance(original_type, UnionType) and any(
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
is_subtype(orig_typ, typ, ignore_pos_arg_names=True)
for orig_typ in original_type.items
):
pass
elif is_equivalent(original_type, typ):
# Assume invariance for a non-callable attribute here. Note
# that this doesn't affect read-only properties which can have
Expand Down
41 changes: 41 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,47 @@ class Base:
class Derived(Base):
__hash__ = 1 # E: Incompatible types in assignment (expression has type "int", base class "Base" defined the type as "Callable[[Base], int]")

[case testOverrideCallableAttributeWithMethod]
from typing import Callable

class Base:
func1: Callable[[str], str]
func2: Callable[[str], str]
func3: Callable[[str], str]

class Derived(Base):
def func1(self, x: str) -> str:
pass

@classmethod
def func2(cls, x: str) -> str:
pass

@staticmethod
def func3(x: str) -> str:
pass
[builtins fixtures/classmethod.pyi]

[case testOverrideCallableUnionAttributeWithMethod]
from typing import Callable, Union

class Base:
func1: Union[Callable[[str], str], str]
func2: Union[Callable[[str], str], str]
func3: Union[Callable[[str], str], str]

class Derived(Base):
def func1(self, x: str) -> str:
pass

@classmethod
def func2(cls, x: str) -> str:
pass

@staticmethod
def func3(x: str) -> str:
pass
[builtins fixtures/classmethod.pyi]

[case testOverridePartialAttributeWithMethod]
# This was crashing: https://github.com/python/mypy/issues/11686.
Expand Down
Loading