[Python-ideas] PEP 380 alternative: A yielding function

Scott Dial scott+python-ideas at scottdial.com
Wed Jul 28 18:54:42 CEST 2010


On 7/27/2010 1:18 PM, Anders J. Munch wrote:
> But suppose you could address the source instead?  Suppose you could
> write yield_if_true in such a way that it did not become a generator
> despite yielding?
...
> Now the example would work with a slight modifiction:
> 
>   def yield_if_true(x):
>       if x:
>           yield_(x)
>   yield_if_true(a)
>   yield_if_true(b)
> 
> The real benefits from a yield_ function come with recursive
> functions.

Except now yield_if_true() is not a generator. So, you have two classes
of "generators" now (top-level/delegated), which breaks all sorts of
things. How would you write izip() with this? You'd have to have a
top-level (yield) version and a delegated (yield_()) version to satisfy
all of the use-cases. I think your yield_() is actually a detriment to
recursive functions. The "yield from" solution is superior in that the
delegated generators are still normal generators to other call sites
that are indifferent to that use case.

I feel that there is no escaping that "for v in g: yield g" and small
variations are an amazingly common pattern that are amazingly naive.
Although for many use cases, it works just fine; the unfortunate
side-effect is that anyone building more clever generators on-top find
themselves victimized by other authors. Creating a "yield from" syntax
gives the other authors a pleasant and explicit shorthand, and provides
for the other use cases automatically.

> I'm guessing
> you could implement 'yield from' as a pure-Python
> function using yield_, making yield_ strictly more powerful

PEP 380 already provides a pure python description of "yield from" using
existing syntax, therefore the assertion that you could implement it
using yield_() provides no measure for how "powerful" your suggestion is.

-- 
Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu



More information about the Python-ideas mailing list