generator/coroutine terminology

Dave Angel davea at davea.name
Tue Mar 31 09:38:16 EDT 2015


On 03/31/2015 09:18 AM, 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.)
>

He did say it was an iterator.  So for a first try, write a for loop:

class Squares:
    def __init__(self):
        self.i = 0
    def __next__(self):
        self.i += 1
        return self.i**2
    def __iter__(self):
        return self

for i in Squares():
     print(i)
     if i > 50:
         break

print("done")


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



More information about the Python-list mailing list