[Python-ideas] iterable.__unpack__ method

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Mon Feb 25 11:32:34 CET 2013


Nick Coghlan <ncoghlan at ...> writes:

> Status quo, 2 items (etc):
> 
>     from itertools import islice
>     iterargs = iter(args)
>     command, subcommand = islice(iterargs, 2) # Grab the first two,
> leave the rest
>     commands[command][subcommand](*iterargs) # Pass the rest to the subcommand

When it comes to getting multiple items from an iterator, I prefer wrapping
things in my own generator function:

def x_iter(iterator,n):
    """Return n items from iterator."""
    
    i=[iterator]*n
    while True:
        try:
            result=[next(i[0])]
        except StopIteration:
            # iterator exhausted immediately, end the generator
            break
        for e in i[1:]:
            try:
                result.append(next(e))
            except StopIteration:
                # iterator exhausted after returning at least one item, but
before returning n
                raise ValueError("only %d value(s) left in iterator, expected
%d" % (len(result),n))
        yield result

Compared to islice, this has the advantage of working properly in for loops:

>>> it=iter(range(1,11))
>>> for c,d in x_iter(it,2):
	print(c,d)

	
1 2
3 4
5 6
7 8
9 10

Maybe one could improve itertools.islice accordingly??

> Proposal, 2 items (etc):
> 
>     iterargs = iter(args)
>     command, subcommand, ... = iterargs # Grab the first two, leave the rest
>     commands[command][subcommand](*iterargs) # Pass the rest to the subcommand
> 

+1  for this. I think it's very readable. I think it should raise differently
though depending on whether iterargs is exhausted right away (StopIteration) or
during unpacking (ValueError).

Best,
Wolfgang 







More information about the Python-ideas mailing list