Skip to content

Commit 70eceea

Browse files
committed
Fix noncommutative joins with bounded TypeVars (#20345)
Fixes #20344
1 parent 3890fc4 commit 70eceea

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed

mypy/join.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -297,10 +297,15 @@ def visit_erased_type(self, t: ErasedType) -> ProperType:
297297
return self.s
298298

299299
def visit_type_var(self, t: TypeVarType) -> ProperType:
300-
if isinstance(self.s, TypeVarType) and self.s.id == t.id:
301-
if self.s.upper_bound == t.upper_bound:
302-
return self.s
303-
return self.s.copy_modified(upper_bound=join_types(self.s.upper_bound, t.upper_bound))
300+
if isinstance(self.s, TypeVarType):
301+
if self.s.id == t.id:
302+
if self.s.upper_bound == t.upper_bound:
303+
return self.s
304+
return self.s.copy_modified(
305+
upper_bound=join_types(self.s.upper_bound, t.upper_bound)
306+
)
307+
# Fix non-commutative joins
308+
return get_proper_type(join_types(self.s.upper_bound, t.upper_bound))
304309
else:
305310
return self.default(self.s)
306311

mypy/test/testtypes.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,6 +1051,35 @@ def test_join_type_type_type_var(self) -> None:
10511051
self.assert_join(self.fx.type_a, self.fx.t, self.fx.o)
10521052
self.assert_join(self.fx.t, self.fx.type_a, self.fx.o)
10531053

1054+
def test_join_type_var_bounds(self) -> None:
1055+
tvar1 = TypeVarType(
1056+
"tvar1",
1057+
"tvar1",
1058+
TypeVarId(-100),
1059+
[],
1060+
self.fx.o,
1061+
AnyType(TypeOfAny.from_omitted_generics),
1062+
INVARIANT,
1063+
)
1064+
any_type = AnyType(TypeOfAny.special_form)
1065+
tvar2 = TypeVarType(
1066+
"tvar2",
1067+
"tvar2",
1068+
TypeVarId(-101),
1069+
[],
1070+
upper_bound=UnionType(
1071+
[
1072+
TupleType([any_type], self.fx.std_tuple),
1073+
TupleType([any_type, any_type], self.fx.std_tuple),
1074+
]
1075+
),
1076+
default=AnyType(TypeOfAny.from_omitted_generics),
1077+
variance=INVARIANT,
1078+
)
1079+
1080+
self.assert_join(tvar1, tvar2, self.fx.o)
1081+
self.assert_join(tvar2, tvar1, self.fx.o)
1082+
10541083
# There are additional test cases in check-inference.test.
10551084

10561085
# TODO: Function types + varargs and default args.

0 commit comments

Comments
 (0)