Skip to content

Commit 8a08e78

Browse files
TH3CHARLiemsullivan
authored andcommitted
Fix incorrect type inference when inherited from Any class (#8019)
Fixes #8001
1 parent c957ac8 commit 8a08e78

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

mypy/checkexpr.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2470,6 +2470,14 @@ def lookup_definer(typ: Instance, attr_name: str) -> Optional[str]:
24702470
else:
24712471
return result
24722472

2473+
# We finish invoking above operators and no early return happens. Therefore,
2474+
# we check if either the LHS or the RHS is Instance and fallbacks to Any,
2475+
# if so, we also return Any
2476+
if ((isinstance(left_type, Instance) and left_type.type.fallback_to_any) or
2477+
(isinstance(right_type, Instance) and right_type.type.fallback_to_any)):
2478+
any_type = AnyType(TypeOfAny.special_form)
2479+
return any_type, any_type
2480+
24732481
# STEP 4b:
24742482
# Sometimes, the variants list is empty. In that case, we fall-back to attempting to
24752483
# call the __op__ method (even though it's missing).

test-data/unit/check-classes.test

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6575,3 +6575,24 @@ class C:
65756575
from typing import Callable
65766576
class C:
65776577
x: Callable[[C], int] = lambda x: x.y.g() # E: "C" has no attribute "y"
6578+
6579+
[case testOpWithInheritedFromAny]
6580+
from typing import Any
6581+
C: Any
6582+
class D(C):
6583+
pass
6584+
6585+
class D1(C):
6586+
def __add__(self, rhs: float) -> D1:
6587+
return self
6588+
6589+
reveal_type(0.5 + C) # N: Revealed type is 'Any'
6590+
6591+
reveal_type(0.5 + D()) # N: Revealed type is 'Any'
6592+
reveal_type(D() + 0.5) # N: Revealed type is 'Any'
6593+
reveal_type("str" + D()) # N: Revealed type is 'builtins.str'
6594+
reveal_type(D() + "str") # N: Revealed type is 'Any'
6595+
6596+
6597+
reveal_type(0.5 + D1()) # N: Revealed type is 'Any'
6598+
reveal_type(D1() + 0.5) # N: Revealed type is '__main__.D1'

0 commit comments

Comments
 (0)