python – 将生成器函数注释为迭代器的混淆
作者:互联网
Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]:
def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1
我写了一个非常简单的打印无限流的例子.我有一个生成器函数,它被传递给另一个函数,然后被调用.
from typing import Iterator
def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1
def print_infinite_stream(inf_iterator: Iterator[int]):
for x in inf_iterator(5):
print(x)
print_infinite_stream(infinite_stream)
使用mypy我得到两个错误:
>错误:Iterator [int]不可调用
>错误:“print_infinite_stream”的参数1具有不兼容的类型“Callable [[int],Iterator [int]]”;预期“迭代器[int]”
我很困惑,为什么我得到这些错误,因为我根据文档工作,并安装了最新的python(3.6.5)和mypy(0.590).这有什么不对?
解决方法:
annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]
发电机功能返回发电机,它们本身不是发电机.如果你这样做:
reveal_type(infinite_stream),你会得到类似Callable [[int],Iterator [int]]的东西.
你想要的是函数的返回值,实际的迭代器.
from typing import Iterator
def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1
def print_infinite_stream(inf_iterator: Iterator[int]):
for x in inf_iterator:
print(x)
print_infinite_stream(infinite_stream(5))
这更有意义,因为现在print_infinite_stream处理任何迭代器,而不仅仅是你的生成器函数.如果您使用reveal_type(infinite_stream(5)),您应该得到类似Iterator [int]的东西,这正是您想要的.
标签:python,type-hinting,mypy 来源: https://codeday.me/bug/20190701/1347126.html