Skip to content

Preserve groupby iterator alternatives for union inputs#16019

Open
JSap0914 wants to merge 1 commit into
python:mainfrom
JSap0914:fix-groupby-union-16018
Open

Preserve groupby iterator alternatives for union inputs#16019
JSap0914 wants to merge 1 commit into
python:mainfrom
JSap0914:fix-groupby-union-16018

Conversation

@JSap0914

@JSap0914 JSap0914 commented Jul 15, 2026

Copy link
Copy Markdown

What

Model the no-key itertools.groupby overload with the input's concrete iterator type, while retaining the existing public groupby[key, item] annotation shape.

Why

For a union such as Sequence[str] | Sequence[int], each produced group is homogeneous at runtime. Preserving the input iterator alternatives prevents the groups from being widened to Iterator[str | int].

Fixes #16018

Tests

  • PATH="$PWD/.venv/bin:$PATH" .venv/bin/pre-commit run --files stdlib/itertools.pyi stdlib/@tests/test_cases/itertools/check_groupby.py
  • PATH="$PWD/.venv/bin:$PATH" .venv/bin/python tests/ty_test.py stdlib/itertools.pyi --python=.venv/bin/python --python-version=3.13 --platform=darwin
  • .venv/bin/python tests/regr_test.py stdlib --python-version 3.13
  • npx pyright@1.1.411 stdlib/@tests/test_cases --pythonversion 3.13 -p pyrightconfig.testcases.json
  • .venv/bin/python -m mypy.stubtest itertools --custom-typeshed-dir . --strict-type-check-only

Note: the new overload is verified with pyright and ty; mypy does not yet propagate the exact iterator type through this overload (assert_type is disabled for mypy in the test case), and mypy_primer is clean.

@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

Comment thread stdlib/itertools.pyi
@overload
def __iter__(self) -> Iterator[_T_co]: ...
@overload
def __iter__(self) -> _IteratorT_co: ... # type: ignore[overload-cannot-match]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't make sense to me

@hauntsaninja hauntsaninja left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not sure i understand this, and i'm not sure how intentional it is that this works for ty. it also might be unsound for elements that compare equal to other types

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.

itertools.groupby turns [A] | [B] into [A | B]

2 participants