如何解决在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。