Skip to content

Commit 9b5b6a8

Browse files
authored
feat(core): Support List.__add__ (#24)
1 parent 1513c93 commit 9b5b6a8

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

python/mlc/core/list.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@ def __setitem__(self, index: int, value: T) -> None:
5454
def __iter__(self) -> Iterator[T]:
5555
return iter(self[i] for i in range(len(self)))
5656

57+
def __add__(self, other: Sequence[T]) -> List[T]:
58+
if not isinstance(other, (list, tuple, List)):
59+
return NotImplemented
60+
result = List(self)
61+
result.extend(other)
62+
return result
63+
64+
def __radd__(self, other: Sequence[T]) -> List[T]:
65+
if not isinstance(other, (list, tuple)):
66+
return NotImplemented
67+
result = List(other)
68+
result.extend(self)
69+
return result
70+
5771
def insert(self, i: int, x: T) -> None:
5872
i = _normalize_index(i, len(self) + 1)
5973
return List._C(b"_insert", self, i, x)

tests/python/test_core_list.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from collections.abc import Sequence
12
from typing import Any
23

34
import pytest
@@ -181,3 +182,19 @@ def test_list_setitem() -> None:
181182
with pytest.raises(IndexError) as e:
182183
a[-5] = 20
183184
assert str(e.value) == "list assignment index out of range: -5"
185+
186+
187+
@pytest.mark.parametrize(
188+
"a, b",
189+
[
190+
(List([1, 2, 3]), [4, 5, 6]),
191+
(List([1, 2, 3]), (4, 5, 6)),
192+
(List([1, 2, 3]), List([4, 5, 6])),
193+
([1, 2, 3], List([4, 5, 6])),
194+
((1, 2, 3), List([4, 5, 6])),
195+
],
196+
)
197+
def test_list_concat(a: Sequence[int], b: Sequence[int]) -> None:
198+
c = a + b # type: ignore[operator]
199+
assert isinstance(c, List)
200+
assert c == [1, 2, 3, 4, 5, 6]

0 commit comments

Comments
 (0)