Skip to content

Commit

Permalink
Fix incorrect join in the presence of Any fallback (#14404)
Browse files Browse the repository at this point in the history
Fixes #11925

This avoids mypy from guessing subtype relationships because of the any
fallback over here:

https://github.com/python/mypy/blob/e1bfb75ed2187db76d51ed875ce953da3ba4d02c/mypy/subtypes.py#L438
  • Loading branch information
hauntsaninja committed Jan 20, 2023
1 parent 9a8c171 commit 8f4da0e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
5 changes: 4 additions & 1 deletion mypy/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT
from mypy.state import state
from mypy.subtypes import (
SubtypeContext,
find_member,
is_equivalent,
is_proper_subtype,
Expand Down Expand Up @@ -101,7 +102,9 @@ def join_instances(self, t: Instance, s: Instance) -> ProperType:
assert new_type is not None
args.append(new_type)
result: ProperType = Instance(t.type, args)
elif t.type.bases and is_subtype(t, s, ignore_type_params=True):
elif t.type.bases and is_proper_subtype(
t, s, subtype_context=SubtypeContext(ignore_type_params=True)
):
result = self.join_instances_via_supertype(t, s)
else:
# Now t is not a subtype of s, and t != s. Now s could be a subtype
Expand Down
6 changes: 1 addition & 5 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,7 @@ def check_context(self, proper_subtype: bool) -> None:
# Historically proper and non-proper subtypes were defined using different helpers
# and different visitors. Check if flag values are such that we definitely support.
if proper_subtype:
assert (
not self.ignore_type_params
and not self.ignore_pos_arg_names
and not self.ignore_declared_variance
)
assert not self.ignore_pos_arg_names and not self.ignore_declared_variance
else:
assert not self.erase_instances and not self.keep_erased_types

Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -3380,3 +3380,15 @@ class A:
T = TypeVar("T")
def type_or_callable(value: T, tp: Union[Type[T], Callable[[int], T]]) -> T: ...
reveal_type(type_or_callable(A("test"), A)) # N: Revealed type is "__main__.A"

[case testJoinWithAnyFallback]
from unknown import X # type: ignore[import]

class A: ...
class B(X, A): ...
class C(B): ...
class D(C): ...
class E(D): ...

reveal_type([E(), D()]) # N: Revealed type is "builtins.list[__main__.D]"
reveal_type([D(), E()]) # N: Revealed type is "builtins.list[__main__.D]"

0 comments on commit 8f4da0e

Please sign in to comment.