Skip to content

Commit

Permalink
Implement radd for MutableList
Browse files Browse the repository at this point in the history
Summary: Add `__radd__` to handle cases like `[] + mutable_list`

Reviewed By: aristidisp

Differential Revision: D66812697

fbshipit-source-id: 5e8cef61913009df530dd7d459c53fa94c0029ed
  • Loading branch information
yoney authored and facebook-github-bot committed Dec 5, 2024
1 parent 7c2ebf2 commit e2ff632
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ class MutableList(MutableSequence[T]):
self: MutableList[MutableMap[Any, Any]],
other: Iterable[T | _ThriftMapWrapper],
) -> MutableList[T]: ...
def __radd__(self, other: Iterable[T]) -> MutableList[T]: ...
def count(self, value: object) -> int: ...
def index(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ cdef class MutableList:
lst.extend(other)
return lst

def __radd__(self, other):
lst = MutableList(self._val_typeinfo, [])
lst.extend(other)
lst._list_data.extend(self._list_data)
return lst

def __deepcopy__(self, memo):
return MutableList(self._val_typeinfo, copy.deepcopy(self._list_data, memo))

Expand Down
21 changes: 21 additions & 0 deletions third-party/thrift/src/thrift/lib/python/test/mutable_list_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,27 @@ def test_add(self) -> None:
self.assertIsInstance(result, MutableList)
self.assertIsNot(result, mutable_list)

def test_radd(self) -> None:
mutable_list = _create_MutableList_i32([])

result_1 = [] + mutable_list
self.assertIsInstance(result_1, MutableList)
self.assertEqual([], result_1)

mutable_list.extend(range(100, 200))
self.assertEqual([], result_1)

result_2 = list(range(100)) + mutable_list
self.assertIsInstance(result_2, MutableList)
self.assertEqual(list(range(200)), result_2)

# Left hand side with wrong type raises `TypeError`
with self.assertRaisesRegex(
TypeError, "is not a <class 'int'>, is actually of type <class 'str'>"
):
# pyre-ignore[58]: Intentional for test
_ = ["1", "2"] + mutable_list

def test_count(self) -> None:
mutable_list = _create_MutableList_i32([1, 2, 1, 1, 3, 2])

Expand Down

0 comments on commit e2ff632

Please sign in to comment.