Skip to content

Preserve sort keys during reflected SortedKeyList multiplication - #258

Closed
Eric3-jp wants to merge 1 commit into
grantjenks:masterfrom
Eric3-jp:fix-keyed-list-reflected-multiplication
Closed

Eric3-jp wants to merge 1 commit into
grantjenks:masterfrom
Eric3-jp:fix-keyed-list-reflected-multiplication

Conversation

@Eric3-jp

Copy link
Copy Markdown

SortedKeyList overrides __mul__, but inherits SortedList.__rmul__. As a result, multiplying on the left drops the custom sort key:

from operator import neg
from sortedcontainers import SortedKeyList

values = SortedKeyList([1, 2, 3], key=neg)
list(values * 2)  # [3, 3, 2, 2, 1, 1]
list(2 * values)  # currently [1, 1, 2, 2, 3, 3]

It can also raise TypeError for values such as dictionaries that require a key function to be ordered. Bind SortedKeyList.__rmul__ to its own __mul__, following the existing __radd__ pattern, so both multiplication directions preserve the key.

Add regression coverage for empty and nonempty inputs, negative/zero/positive counts, and dictionary values ordered by a custom key. The tests also verify that the original list is unchanged and repeated values retain their object identities.

Validation on Python 3.12 / Ubuntu 24.04:

  • All nine new regression cases fail before the fix.
  • Full pytest -q --tb=short: 375 passed, including the regression cases and doctests.
  • Ruff formatting passes for both changed files.
  • doc8, rstcheck, Sphinx HTML build, package build, and twine check pass.
  • Ruff 0.16.8 reports five existing B905 diagnostics and formatting changes in two untouched files (docs/conf.py and src/sortedcontainers/sorteddict.py). The same results were confirmed in a clean checkout of the base commit; this patch adds no new diagnostics.

AI disclosure: This issue was identified during a code review, and the change was prepared and tested with OpenAI Codex.

@Eric3-jp Eric3-jp closed this by deleting the head repository Sep 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant