Skip to content

Add sort before groupby#31

Closed
denini08 wants to merge 1 commit into
Toilal:developfrom
denini08:develop
Closed

Add sort before groupby#31
denini08 wants to merge 1 commit into
Toilal:developfrom
denini08:develop

Conversation

@denini08

@denini08 denini08 commented Jan 24, 2026

Copy link
Copy Markdown
Contributor

Hello!

While reading the code and running some tests, I noticed a small detail that could cause unexpected behavior when the input list is not ordered. The itertools.groupby() function assumes the data is already sorted by the key (docs), but in _group_by_match_index this was not guaranteed.

So I added a sorted() call before the groupby() to make the behavior safe and consistent, regardless of the input order.

Interestingly, the rest of the codebase already follows this same pattern:

I also added a small test that explicitly checks the behavior with unsorted input data, just to make sure this case is always covered.

Thank youfor the project!
I hope this improvement is helpful.

Toilal added a commit that referenced this pull request Jun 28, 2026
itertools.groupby only groups consecutive equal keys, so unordered matches reaching _group_by_match_index split into separate groups and the dict assignment overwrites earlier ones, silently dropping matches. Sort by match_index first (no-op when already ordered), matching the sorted()-before-groupby() convention in rules.py.

Reworked from #31 (rebased, line wrapped, typed test that fails without the fix). Supersedes #31.

Co-authored-by: denini08 <denini08@users.noreply.github.com>
@Toilal

Toilal commented Jun 28, 2026

Copy link
Copy Markdown
Owner

Thanks a lot for catching this, @denini08 — you're absolutely right that itertools.groupby needs sorted input here, and the fix aligns nicely with the existing sorted()-before-groupby() pattern in rules.py.

I've merged a reworked version in #49 (rebased on the current develop, with the line wrapped to fit the 120-char limit and the test adjusted to pass the strict typing/lint gates). You're credited as co-author on the squashed commit.

Closing this one in favour of #49 — much appreciated! 🙏

@Toilal Toilal closed this Jun 28, 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.

2 participants