Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #88383
| Date | 2015-03-31 09:38 -0400 |
|---|---|
| From | Dave Angel <davea@davea.name> |
| Subject | Re: generator/coroutine terminology |
| References | <ff0bc8eb-63e4-40ea-8d31-301625a3d470@googlegroups.com> <mailman.379.1426371862.21433.python-list@python.org> <87y4mznmj8.fsf@elektro.pacujo.net> <55062bda$0$12998$c3e8da3$5496439d@news.astraweb.com> <551a9ebe$0$2987$e4fe514c@dreader35.news.xs4all.nl> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.372.1427809109.10327.python-list@python.org> (permalink) |
On 03/31/2015 09:18 AM, Albert van der Horst wrote:
> In article <55062bda$0$12998$c3e8da3$5496439d@news.astraweb.com>,
> Steven D'Aprano <steve+comp.lang.python@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Re: generator/coroutine terminology albert@spenarnc.xs4all.nl (Albert van der Horst) - 2015-03-31 13:18 +0000
Re: generator/coroutine terminology Dave Angel <davea@davea.name> - 2015-03-31 09:38 -0400
Re: generator/coroutine terminology albert@spenarnc.xs4all.nl (Albert van der Horst) - 2015-03-31 15:03 +0000
Re: generator/coroutine terminology Chris Angelico <rosuav@gmail.com> - 2015-04-01 02:36 +1100
Re: generator/coroutine terminology Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-04-03 17:02 +1100
Re: generator/coroutine terminology albert@spenarnc.xs4all.nl (Albert van der Horst) - 2015-04-18 17:52 +0000
Re: generator/coroutine terminology Paul Rubin <no.email@nospam.invalid> - 2015-04-02 23:46 -0700
csiph-web