Skip to content

itertools' all_equal recipe causes false arg-type failures #15150

Closed
@me-and

Description

@me-and

Bug Report

Adding annotations to the itertools recipe for all_equal results in a false "arg-type" error message from mypy. This can be worked around by adding an intermediate argument, but the intermediate argument doesn't have any functional impact, so I think this must be a bug.

To Reproduce

Playground link: https://mypy-play.net/?mypy=latest&python=3.11&gist=012171f435d6fd0119ac028acc794877

The following two functions, both based on the all_equal recipe in the official Python itertools documentation, work identically. However all_equal_error produces an "arg-type" error from mypy, while all_equal_pass does not.

from itertools import groupby
from typing import TypeVar
from collections.abc import Iterable

T = TypeVar('T')

def all_equal_pass(i: Iterable[T]) -> bool:
    g = groupby(i)
    ans = next(g, True) and not next(g, False)
    return ans
    
def all_equal_error(i: Iterable[T]) -> bool:
    g = groupby(i)
    return next(g, True) and not next(g, False)

Expected Behavior

Either (a) my typing annotations are correct and mypy shouldn't report a problem with either function, or (b) my typing annotations are bogus and mypy should report a problem with both functions.

Actual Behavior

mypy produces the following error:

main.py:14: error: Argument 1 to "next" has incompatible type "groupby[T, T]"; expected "SupportsNext[bool]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

I've reproduced this both on the playground (mypy latest 1.2.0, Python 3.11, default options) and on my Debian testing box (mypy=1.0.1-1, python3.11=3.11.2-6, no command line options, no changes to out-of-the-box configuration).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions