在Python中为itertools.count使用哪种类型?

问题描述

我正在尝试在Python中指定itertool.count对象的类型,就像这样:

from itertools import count

c: count = count()

但是,运行mypy会产生以下错误:

test.py:3: error: Function "itertools.count" is not valid as a type
test.py:3: note: Perhaps you need "Callable[...]" or a callback protocol?
Found 1 error in 1 file (checked 1 source file)

这似乎是由于itertools.count的行为类似于一个函数引起的。但是,它返回一个itertools.count对象,如

所示
In [1]: import itertools
In [2]: type(itertools.count()) is itertools.count
Out[2]: True

然后,我应该如何指定count()的结果类型?

解决方法

itertools.pyi中有以下注释:

_N = TypeVar('_N',int,float)

def count(start: _N = ...,step: _N = ...) -> Iterator[_N]: ...  # more general types?

因此,在您的代码中,您可以这样:

from typing import Iterator
from itertools import count

c: Iterator[int] = count()
c_i: Iterator[int] = count(start=1,step=1)
c_f: Iterator[float] = count(start=1.0,step=0.1)  # since python 3.1 float is allowed

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...