ldb*_*dbo 6 python type-hinting mypy python-3.8
我试图itertool.count在 Python 中指定对象的类型,如下所示:
from itertools import count
c: count = count()
Run Code Online (Sandbox Code Playgroud)
然而,运行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)
Run Code Online (Sandbox Code Playgroud)
这似乎是由于其itertools.count行为类似于函数而引起的。但是,它返回一个itertools.count对象,如下所示
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)
Run Code Online (Sandbox Code Playgroud)
那么,我应该如何指定结果的类型呢count()?
中有如下注释itertools.pyi:
_N = TypeVar('_N', int, float)
def count(start: _N = ...,
step: _N = ...) -> Iterator[_N]: ... # more general types?
Run Code Online (Sandbox Code Playgroud)
因此,在您的代码中,您可以这样做:
_N = TypeVar('_N', int, float)
def count(start: _N = ...,
step: _N = ...) -> Iterator[_N]: ... # more general types?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1339 次 |
| 最近记录: |