Skip to content

Commit 1a99ce2

Browse files
authored
[mypyc] Fix comparison of tuples with different lengths (#19372)
When comparing tuples, their lengths are now compared and their contents are only compared if their lengths are equal. Otherwise, when they have different lengths, the comparison always evaluates to `False`.
1 parent 1bf186c commit 1a99ce2

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

mypyc/irbuild/ll_builder.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1507,6 +1507,10 @@ def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int = -1) -> Val
15071507
assert isinstance(lhs.type, RTuple) and isinstance(rhs.type, RTuple)
15081508
equal = True if op == "==" else False
15091509
result = Register(bool_rprimitive)
1510+
# tuples of different lengths
1511+
if len(lhs.type.types) != len(rhs.type.types):
1512+
self.add(Assign(result, self.false() if equal else self.true(), line))
1513+
return result
15101514
# empty tuples
15111515
if len(lhs.type.types) == 0 and len(rhs.type.types) == 0:
15121516
self.add(Assign(result, self.true() if equal else self.false(), line))

mypyc/test-data/run-tuples.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,22 @@ def f7(x: List[Tuple[int, int]]) -> int:
203203
def test_unbox_tuple() -> None:
204204
assert f7([(5, 6)]) == 11
205205

206+
def test_comparison() -> None:
207+
assert ('x','y') == ('x','y')
208+
assert not(('x','y') != ('x','y'))
209+
210+
assert ('x','y') != ('x','y',1)
211+
assert not(('x','y') == ('x','y',1))
212+
213+
assert ('x','y',1) != ('x','y')
214+
assert not(('x','y',1) == ('x','y'))
215+
216+
assert ('x','y') != ()
217+
assert not(('x','y') == ())
218+
219+
assert () != ('x','y')
220+
assert not(() == ('x','y'))
221+
206222
# Test that order is irrelevant to unions. Really I only care that this builds.
207223

208224
class A:

0 commit comments

Comments
 (0)