*-unpacking (Re: Fun with fancy slicing)

Greg Ewing (using news.cis.dfn.de) g2h5dqi002 at sneakemail.com
Fri Oct 3 01:12:58 EDT 2003


Alex Martelli wrote:
> How sweet it would be to be able to unpack by coding:
>     head, *tail = alist

Indeed! I came across another use case for this
recently, as well. I was trying to parse some
command strings of the form

    command arg arg ...

where some commands had args and some didn't.
I wanted to split the command off the front
and keep the args for later processing once
I'd decoded the command. My first attempt
went something like

   command, args = cmdstring.split(" ", maxsplit = 1)

but this fails when there are no arguments,
because the returned list has only one element
in that case.

It would have been very nice to be able to
simply say

   command, *args = cmdstring.split()

and get the command as a string and a
list of 0 or more argument strings.

I really ought to write a PEP about this...

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list