问题描述
我正在尝试在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