[Python-ideas] iterable.__unpack__ method

Larry Hastings larry at hastings.org
Sun Feb 24 12:25:56 CET 2013


On 02/23/2013 11:38 PM, Nick Coghlan wrote:
> 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

Or

     command, subcommand = next(iterargs), next(iterargs)

or

     command = next(iterargs)
     subcommand = next(iterargs)

These don't require the manual counting, nor do they feature the 
"discontinuity" you mentioned.  FWIW I don't think this problem is bad 
enough, nor this idiom used frequently enough, to warrant new syntax.  
But I've been wrong before.


I was musing on this topic and came up with what is probably a terrible 
alternate approach.  What if there was some way for the RHS to know what 
the LHS was asking for in a destructuring assignment? Something like

     def __next_n__(self, n):
         "Returns a tuple of the next n items from this iterator."

and if the object doesn't provide __next_n__ you fall back to the 
current explicit PyIter_Next() calls and failing if there aren't enough 
/ there are too many.  If we had this, we could make the second argument 
to islice() optional; it could infer how many items you wanted.  (I 
don't think the "a, b, *c, d = rhs" form is relevant here as you'd 
always consume everything from rhs.)

I'm not sure how bad an idea this is.  But complicating the iterator 
protocol for this marginal problem seems like a pretty bad idea.


//arry/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130224/49e12b1a/attachment.html>


More information about the Python-ideas mailing list