send() to a generator in a "for" loop with continue(val)??
Peter Otten
__peter__ at web.de
Sat Apr 18 05:44:27 EDT 2009
Dale Roberts wrote:
> I've started using generators for some "real" work (love them!), and I
> need to use send() to send values back into the yield inside the
> generator. When I want to use the generator, though, I have to
> essentially duplicate the machinery of a "for" loop, because the "for"
> loop does not have a mechanism to send into the generator. Here is a
> toy example:
>
> def TestGen1():
> for i in xrange(3):
> sendval = yield i
> print " got %s in TestGen()" % sendval
>
> g = TestGen1()
> sendval = None
> try:
> while True:
> val = g.send(sendval)
> print 'val in "while" loop %d' % val
> sendval = val * 10
> except StopIteration: pass
>
> I have to explicitly create the generator with an assignment, send an
> initial None to the generator on the first go, then have to catch the
> StopIteration exception. In other words, replicate the "for"
> mechanism, but use send() instead of next().
>
> It would be nice if I could just do this instead:
>
> for val in TestGen1():
> print 'val in "for" loop %d' % val
> continue(val*10)
>
> ...or something similar. Is this an old idea? Has it been shot down in
> the past already? Or is it worth pursuing? I Googled around and saw
> one hit here:
> http://mail.python.org/pipermail/python-ideas/2009-February/003111.html,
> but not much follow-up.
>
> I wonder if people want to keep the idea of an "iterator" style
> generator (where send() is not used) separate from the idea of a "co-
> routine" style generator (where send() is used). Maybe combining the
> two idioms in this way would cause confusion?
>
> What do folks think?
If it were up to me I'd rip out send() immediatly. At first I thought I
would see a compelling use case and be enlightened, but it never happened.
I just grepped the python 3 source for '= yield' and the only matches were
in the unit tests for generators and parser.
Let it die while it hasn't polluted the wider code base.
Peter
More information about the Python-list
mailing list