Junior — Middle
Is it possible to implement a generator function in a programming language without using the yield keyword?
sobes.tech AI
Answer from AI
Yes, a generator function in Python can be implemented without using the yield keyword, for example, by using a class that implements the iterator protocol. Such a class should have __iter__() and __next__() methods, which return the next element of the sequence on each call.
An example of implementing a Fibonacci number generator without yield:
class Fib:
def __init__(self, n):
self.n = n
self.i = 0
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.i >= self.n:
raise StopIteration
self.i += 1
a = self.a
self.a, self.b = self.b, self.a + self.b
return a
for num in Fib(5):
print(num)
Thus, a generator can be manually implemented through an iterator, without yield. However, yield simplifies writing such functions.