Reputation:
Couldn't all generators be implemented like simple iterator OBJECTS? Why has been introduced a specific solution (YIELD) for a generic problem?
class Generator:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
Thank you
Upvotes: 0
Views: 88
Reputation: 20792
Generally, whenever a special idea (in the sense of not so general) is crystal-clear to understand and easy to write, then it is simpler to use than the more general idea, and it leads to more dense and more understandable code. (This is what also all the play with syntax is. Think about how much more readable is 1 + 2
vs. plus(1, 2)
or 1.plus(2)
. It is sometime called a syntactic sugar, but it is extremely important when it comes to make the code more understandable.)
Think also about the iterators you have mentioned. They are extremely easy to use especially in the case when you do not need to write them. Otherwise, you can make a mistake even when writing iterators. Generators are special also in the sense they are rather simple. This way, the function with yield can probably be optimized better than the general class that implements an iterator.
Compare the following (example) solutions that generate the wanted number of filenames:
class Fnames:
def __init__(self, prefix, cnt):
self.prefix = prefix
self.i = 0
self.cnt = cnt
def __next__(self):
if self.i >= self.cnt:
raise StopIteration
fname = '{}{:04}'.format(self.prefix, self.i)
self.i += 1
return fname
def __iter__(self):
return self
for fname in Fnames('file', 5):
print(fname)
print('--------------------------------------------------- the same')
def fnames(prefix, cnt):
for i in range(cnt):
yield '{}{:04}'.format(prefix, i)
for fname in fnames('file', 5):
print(fname)
(It produces...)
file0000
file0001
file0002
file0003
file0004
--------------------------------------------------- the same
file0000
file0001
file0002
file0003
file0004
Notice that the generator solution takes about 3 lines of code while the iterator class is about 5 times longer. And you have to study the class code at least for a while to recognize that it is an iterator and what it does.
Upvotes: 3