Is it intended that the use of yield mandates the return type Iterator?
For example, if I want the squares of numbers:
def get_squares(n: int) -> Iterable[int]:
return [i**2 for i in range(n)]
I cannot reimplement it as an iterator:
def get_squares(n: int) -> Iterable[int]:
for i in range(n):
yield i**2
without getting Iterator function return type expected for "yield" (even if Iterator actually is a subclass of Iterable).
However, it works with yield from:
def get_squares(n: int) -> Iterable[int]:
yield from (i**2 for i in range(n))
What is the reasoning?
Is it intended that the use of
yieldmandates the return typeIterator?For example, if I want the squares of numbers:
I cannot reimplement it as an iterator:
without getting
Iterator function return type expected for "yield"(even ifIteratoractually is a subclass ofIterable).However, it works with
yield from:What is the reasoning?