can Python be useful as functional?
Duncan Booth
duncan.booth at invalid.invalid
Tue Sep 18 09:41:03 CEST 2007
"Rustom Mody" <rustompmody at gmail.com> wrote:
> On 9/18/07, Alex Martelli <aleax at mac.com> wrote:
>> Rustom Mody <rustompmody at gmail.com> wrote:
>>
>> > Can someone help? Heres the non-working code
>> >
>> > def si(l):
>> > p = l.next()
>> > yield p
>> > (x for x in si(l) if x % p != 0)
>> >
>> > There should be an yield or return somewhere but cant figure it out
>>
>> Change last line to
>>
>> for x in (x for x in si(l) if x % p != 0): yield x
>
>
> Thanks but why does
>
> (yield(x) for x in si(l) if x % p != 0)
>
> not work? I would have expected generator expression to play better
> with generators.
Why should it? It evaluates the expression which returns an object that
just happens to be a generator and then as with any other expression
that isn't assigned or returned it throws away the result.
> More generally, if one wants to 'splice in' a generator into the body
> of a generator, is there no standard pythonic idiom?
Yes there is, as Alex showed you the standard python idiom for a
generator to yield all elements of an iteratable (whether it is a
generator or any other iterable) is:
for somevar in iterable: yield somevar
There have been various proposals in the past such as 'yield from
iterable', but there doesn't seem any compelling case to introduce a new
confusing syntax: the existing syntax works, and adding a special syntax
wouldn't open the door to any performance benefits since the
implementation would have to be pretty much the same (at most you would
save a couple of local variable accesses).
More information about the Python-list
mailing list