[Python-ideas] iterable.__unpack__ method

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Feb 24 17:42:20 CET 2013


On 24 February 2013 06:24, Guido van Rossum <guido at python.org> wrote:
> On Saturday, February 23, 2013, Nick Coghlan wrote:
>> On Sun, Feb 24, 2013 at 12:12 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> > I definitely like Terry's idea of using ", ..." to say "and ignore the
>> > rest". Simple, elegant and can be restricted to the last element so it
>> > works
>> > with infinite iterators and large sequences. It also allows incremental
>> > unpacking of ordinary iterators.
>>
>> I want to expand on this a bit now I'm back on a real computer, since
>> it wasn't immediately obvious to me how well the ", ..." proposal
>> supports incremental unpacking, but it became clear once I thought of
>> this simple example:
>>
>>     iterargs = iter(args)
>>     command, ... = iterargs # Grab the first element, leave the rest
>> in the iterator
>>     commands[command](*iterargs) # Pass the rest to the command
>
> But is that really so much better than
>
>   command = next(iterargs)
>   # etc.

Calls to next() need to be wrapped in try/except StopIteration (it's a
bad idea to leak these exceptions). So then it becomes:

  try:
       command = next(iterator)
  except StopIteration:
      raise ValueError('need more than 0 values to unpack')

Presumably with this proposal

  command, ... = iterator

would raise a ValueError if the iterator is empty.


Oscar



More information about the Python-ideas mailing list