[Python-ideas] [Python-Dev] yield * (Re: Missing operator.call)

Steven D'Aprano steve at pearwood.info
Sun Feb 8 23:20:48 CET 2009

Antoine Pitrou wrote:
> Steven D'Aprano <steve at ...> writes:
>> The advantage is even more obvious when married with a generator expression:
>> yield from (3*x for x in seq if x%2 == 1)
>> instead of:
>> for x in seq:
>>      if x%2 == 1:
>>          yield 3*x
> But the former will be slower than the latter, because it constructs an
> intermediate generator only to yield it element by element.

The "yield from" syntax hasn't even been approved, let alone 
implemented, and you're already complaining it's slow? Talk about 
premature optimization!

That's a criticism of *generator expressions*, not the suggested syntax. 
They're popular because most people prefer the large benefits in 
readability and convenience over the minuscule cost in generating them, 
particularly since often that cost is paid somewhere else: the caller 
builds the generator expression and passes the resulting iterator into 
your function, which merely iterates over it.

And the cost is small:

[steve at ando ~]$ python -m timeit -s "seq = range(500)" "(3*x for x in 
seq if x%2 == 1)"
1000000 loops, best of 3: 0.611 usec per loop


More information about the Python-ideas mailing list