[Python-Dev] Generator methods - "what's next" ?
firephoenix at wanadoo.fr
Sun Apr 5 19:25:56 CEST 2009
Stephen J. Turnbull a écrit :
> Firephoenix writes:
> > I'm a little confused by the recent changes to the generator system...
> Welcome to the club. It's not easy even for the gurus. See the PEP
> 380 ("yield from") discussions (mostly on Python-Ideas).
> > But I noticed then that all the other methods of the generator had
> > stayed the same (send, throw, close...), which gives really weird (imo)
> > codes :
> > next(it)
> > it.send(35)
> > it.throw(Exception())
> > next(it)
> > ....
> > Browsing the web, I've found people troubled by that asymmetry, but no
> > remarks on its causes nor its future...
> Well, this kind of discussion generally belongs on c.l.py, but as far
> as I know, .next() is still present for generators but it's spelled
> .send(None). See PEP 342. It seems to me that the rationale for
> respelling .next() as .__next__() given in PEP 3114 doesn't apply to
> .send() and .throw(), since there is no syntax which invokes those
> methods magically.
> Also note that since next() takes no argument, it presumes no
> knowledge of the implementation of the iterator. So specification as
> a function called "on" the iterator seems natural to me. But .send()
> and .throw() are only useful if you know the semantics of their
> arguments, ie, the implementation of the generator. Thus using method
> syntax for them seems more natural to me.
> If you have some concrete suggestions you want to follow up to
> Python-Dev with, two remarks:
> The code presented above is weird because that code is weird, not
> because the generator methods are messed up. Why would you ever write
> that code? You need a plausible use case, one where a generator is
> the natural way to write the code, but it's not explicitly iterative.
> Second, the whole trend is the other direction, fitting generators
> naturally into Python syntax without using explicit invocation of
> methods. Again, PEP 380 is an example (though rather specialized).
> As is the expression form of yield (half-successful in that no
> recv() syntax or builtin is needed, although .send() seems to be). So
> the use case requested above will need to be compelling.
Whoups, now that you mention it, I discover other mailing-lists seemed
more suitable for this subject... sorry
Actually I ran over an example like the following, in the case of a
"reversed generator" that has to be activated by a first call to "next",
before we're able to send data to the yield expression it has encountered.
But as you mention, send(None) would work as well, and this kind of
"setup operation" had better be hidden in a function decorator or
something like that.
> next(it) # init phase
More information about the Python-Dev