Skip to content

Commit cf93a46

Browse files
committed
Let extend handle the duplicates of an in-place multiplication
`values *= 2` repeats every item once, which is what `values.extend(values)` does. Routing the repeat through extend keeps the duplicate policy in one place and removes the ValueError that CodeQL flagged inside __imul__. The pop test asserted on the calls themselves. It stores the popped values first so the asserts have no side effects.
1 parent 0af9936 commit cf93a46

2 files changed

Lines changed: 7 additions & 6 deletions

File tree

‎_python_utils_tests/test_containers.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,8 +301,9 @@ def test_unique_list_pop() -> None:
301301
values: containers.UniqueList[int] = containers.UniqueList(
302302
1, 2, 3, on_duplicate='raise'
303303
)
304-
assert values.pop() == 3
305-
assert values.pop(0) == 1
304+
last: int = values.pop()
305+
first: int = values.pop(0)
306+
assert (last, first) == (3, 1)
306307
assert values == [2]
307308
assert 1 not in values
308309
assert 3 not in values

‎python_utils/containers.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -534,8 +534,8 @@ def __imul__(
534534
Multiplies the list in place without ever repeating an item.
535535
536536
A count below 1 empties the list, as it does for a regular list. A
537-
count above 1 would repeat every item, so those repeats are handled
538-
as duplicates.
537+
count above 1 would repeat every item, so the repeat goes through
538+
`extend` and follows `on_duplicate`.
539539
540540
Args:
541541
value (typing.SupportsIndex): The number of times to repeat.
@@ -550,8 +550,8 @@ def __imul__(
550550
count: int = operator.index(value)
551551
if count < 1:
552552
self.clear()
553-
elif count > 1 and self and self.on_duplicate == 'raise':
554-
raise ValueError(f'Duplicate values: {self._set}')
553+
elif count > 1:
554+
self.extend(self)
555555

556556
return self
557557

0 commit comments

Comments
 (0)