I'm trying out mypy for some utils functions in my project, but I'm having trouble with this function that combines groupby and next.
This is the function code:
from itertools import groupby
from typing import Iterable, Any
def all_same(iterable: Iterable[Any]) -> bool:
"""Return True if all elements in iterable are equal
>>> all_same([3, 3, 3])
True
>>> all_same([3, 3, 1])
False
>>> all_same([])
True
>>> all_same(['a', 'a'])
True
"""
g = groupby(iterable)
return bool(next(g, True)) and not bool(next(g, False))
I keep getting this error about it not being able to infer the type argument 1 of "next"
:
$ mypy testing.py
testing.py: note: In function "all_same":
testing.py:17: error: Cannot infer type argument 1 of "next"
I figure it means it can't infer the type of g
here, right?
I'm having trouble to understand if this a problem in my type annotations or in type annotations for groupby
.
For reference, this is the type annotation for groupby
:
@overload
def groupby(iterable: Iterable[_T]) -> Iterator[Tuple[_T, Iterator[_T]]]: ...
So this means, "groupby takes an iterable of type T, and returns an iterator of tuples containing two items: (one item of type T, an iterator of the objects of type T)".
Looks good to me, but then mypy should be able to infer the first argument of next
as Iterator[Tuple[Any, Iterator[Any]]]
, right?
What am I missing?