Skip to content

Optional key to itertools.groupby #6377

Closed
@achampion

Description

@achampion

itertools.groupby has an @overload type signature but this seems makes Optional[Callable[[T], S]] not match, e.g.:

def fn(iterable: Iterable[T], key: Optional[Callable[[T], S]] = None):
    iterator: Iterator[Tuple[S, Iterator[T]]] = itertools.groupby(iterable, key)

Fails with:

error: Argument 2 to "groupby" has incompatible type "Optional[Callable[[T], S]]"; expected "Callable[[T], S]"

The revealed type of itertools.groupby:

Overload(def [_T] (iterable: typing.Iterable[_T`-1]) -> typing.Iterator[Tuple[_T`-1, typing.Iterator[_T`-1]]], def [_T, _S] (iterable: typing.Iterable[_T`-1], key: def (_T`-1) -> _S`-2) -> typing.Iterator[Tuple[_S`-2, typing.Iterator[_T`-1]]])

It is legitimate to explicitly pass None as key, so is this expected behaviour?
You can do a similar @overload for myfunc to overcome the error.

Versions:
Python 3.7.2
MyPy 0.670

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions