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

2024-09-28 19:03:17 发布

您现在位置: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的行为类似于函数。但是,它返回一个itertools.count对象,如下所示

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

那么,我应该如何指定count()结果的类型呢


Tags: 对象infrompytestimport类型is
1条回答
网友
1楼 · 发布于 2024-09-28 19:03:17

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

相关问题 更多 >