Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5405

Re: I don't understand generator.send()

References <1k19ubi.dwyvio12tkc4kN%see@sig.for.address> <BANLkTi=TWSY-Lg9ovuZEPDZWv1QXtL1UKQ@mail.gmail.com> <BANLkTi=c8mzk-n7sD=mSAPoFzfYcd5TS_A@mail.gmail.com> <BANLkTinxnzSeev8awbO7h5HW+QWeJOK88g@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-05-14 21:03 -0600
Subject Re: I don't understand generator.send()
Newsgroups comp.lang.python
Message-ID <mailman.1578.1305428652.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, May 14, 2011 at 7:17 PM, Chris Angelico <rosuav@gmail.com> wrote:
> You're right. It needs a while loop instead of the if (and some slight
> reordering):
>
> def ints():
>   i=0
>   queue=[]
>   while True:
>       if queue:  # see other thread, this IS legal and pythonic and
> quite sensible
>           sent=(yield queue.pop(0))
>       else:
>           sent=(yield i)
>           i+=1
>       while sent is not None:
>           queue.append(sent)
>           sent=(yield None)  # This is the return value from gen.send()
>
> That should work.

Yeah, that should do it.  But this is so much easier to get right and
to understand:

import itertools

class Ints(object):

    def __init__(self):
        self.ints = itertools.count()
        self.queue = []

    def __iter__(self):
        return self

    def next(self):
        if self.queue:
            return self.queue.pop(0)
        else:
            return self.ints.next()

    def insert(self, x):
        self.queue.append(x)

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

I don't understand generator.send() see@sig.for.address (Victor Eijkhout) - 2011-05-14 19:08 -0500
  Re: I don't understand generator.send() "OKB (not okblacke)" <brenNOSPAMbarn@NObrenSPAMbarn.net> - 2011-05-15 00:38 +0000
  Re: I don't understand generator.send() Chris Angelico <rosuav@gmail.com> - 2011-05-15 10:47 +1000
    Re: I don't understand generator.send() see@sig.for.address (Victor Eijkhout) - 2011-05-14 20:40 -0500
  Re: I don't understand generator.send() Chris Rebert <crebert@ucsd.edu> - 2011-05-14 17:47 -0700
  Re: I don't understand generator.send() Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-14 18:57 -0600
  Re: I don't understand generator.send() Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-14 19:05 -0600
  Re: I don't understand generator.send() Chris Angelico <rosuav@gmail.com> - 2011-05-15 11:17 +1000
  Re: I don't understand generator.send() Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-14 21:03 -0600

csiph-web