[Python-ideas] Generator unpacking

Erik python at lucidity.plus.com
Fri Feb 12 18:01:11 EST 2016


On 12/02/16 19:54, Andrew Barnert via Python-ideas wrote:
> Meanwhile, you can always write the expanded version out explicitly. (And you can leave off the first line when you know c is already an iterator.) Or you can use itertools.islice to make it more compact:
>
>      >>> a, b = itertools.islice(c, 2)
>      >>> rest = c

Why not just have an itertools.unpack() - a simple version without 
argument checking:

def unpack(seq, num):
   it = iter(seq)
   yield from (i[1] for i in zip(range(num), it))
   yield it

foo, bar, rest = unpack([1, 2, 3, 4, 5, 6], 2)

Because it's in itertools, the expectation is that it has something to 
do with iterators so the final return value always being an iterator 
regardless of the original sequence type is reasonable (and is perhaps 
the only justification for putting it in itertools in the first place ;) ).

E.




More information about the Python-ideas mailing list