有限可迭代的类型提示

act*_*nda 9 python iterable type-hinting

我的函数foo接受一个things在内部变成列表的参数。

def foo(things):
    things = list(things)
    # more code
Run Code Online (Sandbox Code Playgroud)

list构造函数接受任何可迭代。

但是,注释thingswithtyping.Iterable并没有给用户一个线索,即迭代必须是有限的,而不是像itertools.count().

在这种情况下使用的正确类型提示是什么?

Gio*_*ous 9

我不知道在 Python 中实现此目的的任何可能方法,因为您无法在类型提示中提供此类约束。


但是,该Collection类型可能在您的上下文中作为一种解决方法有用:

class collections.abc.Collection

用于大小可迭代容器类的 ABC。

这要求对象具有 a __len__,这是比有限的更严格的要求。例如,有限生成器不算作Collection