【发布时间】:2016-06-29 03:55:54
【问题描述】:
我正在我的项目中尝试 mypy 的一些 utils 函数,但我在使用这个结合了 groupby 和 next 的函数时遇到了问题。
这是功能代码:
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))
我不断收到关于无法推断 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"
我认为这意味着它无法在这里推断g 的类型,对吧?
我很难理解这是否是我的类型注释或groupby 的类型注释中的问题。
供参考,这里是the type annotation for groupby:
@overload
def groupby(iterable: Iterable[_T]) -> Iterator[Tuple[_T, Iterator[_T]]]: ...
所以这意味着,“groupby 接受一个 T 类型的迭代器,并返回一个包含两个项目的元组迭代器:(一个 T 类型的项目,一个 T 类型的对象的迭代器)”。
对我来说看起来不错,但是 mypy 应该能够将next 的第一个参数推断为Iterator[Tuple[Any, Iterator[Any]]],对吧?
我错过了什么?
【问题讨论】: