Marko Rauhamaa wrote: > Chris Angelico <ros...@gmail.com>: > >> On Sun, Mar 15, 2015 at 9:15 AM, Marko Rauhamaa <ma...@pacujo.net> wrote: >>> Is it necessary/useful for a Python application programmer to be >>> conscious of the different types of iterator? What mistaken usage >>> could arise if the application just treated all iterators as, well, >>> iterators? >> >> If you treat them all as iterators, then you're safe, because that's >> the lowest common denominator. But there are a number of other >> iterators that have more features, including files, generators, etc. > > What features do generator iterators provide on top of generic > iterators?
The biggest difference is syntactic. Here's an iterator which returns a never-ending sequence of squared numbers 1, 4, 9, 16, ... class Squares: def __init__(self): self.i = 0 def __next__(self): self.i += 1 return self.i**2 def __iter__(self): return self Here's the same thing written as a generator: def squares(): i = 1 while True: yield i**2 i += 1 Four lines, versus eight. The iterator version has a lot of boilerplate (although some of it, the two-line __iter__ method, could be eliminated if there was a standard Iterator builtin to inherit from). Here's a more complicated example: class Randoms: def __init__(self): self.finished = False def __next__(self): x = random.random() if x > 0.5: self.finished = True if self.finished: raise StopIteration else: return x def __iter__(self): return self def randoms(): x = random.random() while x < 0.5: yield x x = random.random() Generators, as a rule, are significantly easier to write, understand, and debug. There's nothing they can do that can't be done with an iterator class, but the fiddly, unexciting bits related to halting and resuming and saving state are all handled for you, allowing you to concentrate on the behaviour you want, not the boilerplate. -- Steven -- https://mail.python.org/mailman/listinfo/python-list