generator/coroutine terminology

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Apr 3 02:02:35 EDT 2015


On Wednesday 01 April 2015 00:18, Albert van der Horst wrote:

> In article <55062bda$0$12998$c3e8da3$5496439d at news.astraweb.com>,
> Steven D'Aprano  <steve+comp.lang.python at pearwood.info> wrote:

>>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.)


Ah, sorry about that!

Usage is:

it = Squares()  # create an iterator
print(next(it))  # print the first value
x = next(it)  # extract the second
while x < 100:
    print(x)
    x = next(it)


Beware of doing this:

for x in Squares():
    print(x)

since Squares is an *infinite* generator, it will continue for ever if you 
let it. Fortunately you can hit Ctrl-C to interrupt the for loop at any 
point.

In Python 2, you will need to rename __next__ to just next without the 
double-leading-and-trailing underscores.


>>Here's the same thing written as a generator:
>>
>>def squares():
>>    i = 1
>>    while True:
>>        yield i**2
>>        i += 1

And for this one:

it = squares()  # create the iterator
print(next(it))  # print the first value
x = next(it)  # extract the second
while x < 100:
    print(x)
    x = next(it)


Usage is pretty much exactly the same.


-- 
Steve




More information about the Python-list mailing list