PEP proposal: sequence expansion support for yield statement: yield *
Ken Seehart
k.seehart at partner.samsung.com
Wed Apr 20 15:34:24 EDT 2016
Currently the common pattern for yielding the elements in a sequence is as follows:
for x in sequence: yield x
I propose the following replacement (the result would be identical):
yield *sequence
The semantics are somewhat different from argument expansion (from which the syntax is borrowed), but intuitive: yield all of the elements of a sequence (as opposed to yield the sequence as a single item). This doesn't appear to have any syntactical collisions, as it is currently a syntax error.
Motivation: More compact notation, and the compiler can produce more efficient bytecode than the former representation (the loop overhead is omitted). This pattern is very common in recursive generators, so a compact notation would be nice.
Also, there is precedent: the proposed notation is implemented in javascript with identical semantics (though in javascript, the conventional spacing is different: yield* sequence ).
Examples:
yield *(1,2,3)
... instead of :
yield 1; yield 2; yield 3
... or:
for x in (1,2,3): yield x
yield *chain(seq1, seq2)
... instead of :
for x in chain(seq1, seq2) yield x
~ Ken Seehart
More information about the Python-list
mailing list