python / python/typeshed

Mypy complains about the `all_equal` recipe from the itertools docs

Open
#10,980 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stubs: false positive
Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

The following function is given as a recipe in the itertools docs, indicating that it's an idiomatic usage of groupby:

from itertools import groupby

def all_equal(iterable):
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

I think the correct way of adding type annotations to this function would be as follows, since it will work on arbitrary iterables:

from collections.abc import Iterable
from itertools import groupby

def all_equal(iterable: Iterable[object]) -> bool:
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

Unfortunately, however, mypy complains about this function:

error: Argument 1 to "next" has incompatible type "groupby[object, object]"; expected "SupportsNext[bool]"  [arg-type]

(Mypy gives a similar error if I use Iterable[Any] instead of Iterable[object] for the argument annotation.)

Perhaps we should consider copy-and-pasting all the itertools recipes into our test_cases directory. They're all meant to be idiomatic uses of itertools, so if any of them fail to type check, there's probably a problem somewhere.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the itertools docs' all_equal recipe with the proposed Iterable annotation and the current mypy behavior. Review the existing test_cases directory and consider adding the itertools recipes there, using successful type checking of the recipes as the completion criterion.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing, tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.