yield_all needed in Python

Jeremy Bowers jerf at jerf.org
Wed Mar 2 10:04:33 EST 2005


On Wed, 02 Mar 2005 22:54:14 +1000, Nick Coghlan wrote:

> Douglas Alan wrote:
>> Steve Holden <steve at holdenweb.com> writes:
>>>Guido has generally observed a parsimony about the introduction of
>>>features such as the one you suggest into Python, and in particular
>>>he is reluctant to add new keywords - even in cases like decorators
>>>that cried out for a keyword rather than the ugly "@" syntax.
>> 
>> In this case, that is great, since I'd much prefer
>> 
>>    yield *gen1(arg)
> 
> If you do write a PEP, try to get genexp syntax supported by the yield keyword.
> 
> That is, the following currently triggers a syntax error:
>    def f():
>      yield x for x in gen1(arg)

Hmmmm.

At first I liked this, but the reason that is a syntax error is that it is
"supposed" to be

def f():
    yield (x for x in gen1(arg))

which today on 2.4 returns a generator instance which will in turn
yield one generator instance from the genexp, and I am quite uncomfortable
with the difference between the proposed behaviors with and without the
parens.

Which sucks, because at first I really liked it :-)

We still would need some syntax to say "yield this 'in place' rather than
as an object".

Moreover, since "yield" is supposed to be analogous to "return", what does

    return x for x in gen1(arg)

do? Both "it returns a list" and "it returns a generator" have some
arguments in their favor.

And I just now note that any * syntax, indeed, any syntax at all will
break this.

You know, given the marginal gains this gives anyway, maybe it's best off
to just observe that in the event that this is really important, it's
possible to hand-code the short-circuiting without too much work, and let
people write a recipe or something.

def genwrap(*generators):
    while generators:
        try:
            returnedValue = generators[-1].next()
            if hasattr(returnedValue, 'next'):
                generators.append(returnedValue)
                continue
            yield returnedValue
        except StopIteration:
            generators.pop()

Not tested at all because the wife is calling and I gotta go :-)




More information about the Python-list mailing list