Python 中的 itertools.count 使用什么类型?
What type to use for itertools.count in Python?
我正在尝试在 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
表现得像一个函数引起的。但是,它 returns 是一个 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
我正在尝试在 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
表现得像一个函数引起的。但是,它 returns 是一个 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