generator/coroutine terminology
Albert van der Horst
albert at spenarnc.xs4all.nl
Tue Mar 31 09:18:54 EDT 2015
In article <55062bda$0$12998$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>Marko Rauhamaa wrote:
>
>> Chris Angelico <rosuav at gmail.com>:
>>
>>> On Sun, Mar 15, 2015 at 9:15 AM, Marko Rauhamaa <marko at 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
You should give an example of usage. As a newby I'm not up to
figuring out the specification from source for
something built of the mysterious __ internal
thingies.
(I did experiment with Squares interactively. But I didn't get
further than creating a Squares object.)
>
>
>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.
This is illuminating. Thanks.
>
>--
>Steven
Groetjes Albert
>
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst
More information about the Python-list
mailing list