[Python-Dev] Half-baked proposal: * (and **?) in assignments

Alex Martelli aleax@aleax.it
Sun, 24 Nov 2002 09:03:20 +0100

On Sunday 24 November 2002 03:00 am, Brett Cannon wrote:
> #2 is the better option.  But it that complicated to write as a function::
> 	def peel(iterator, arg_cnt):
> 		if not hasattr(iterator, 'next'):
> 			iterator = iter(iterator)
> 		for num in xrange(arg_cnt):
> 			yield iterator.next()
> 		else:
> 			yield iterator

I think this generator can be simplified without altering its behavior:

def peel(iterator, arg_cnt=2):
    iterator = iter(iterator)
    for num in xrange(arg_cnt):
        yield iterator.next()
    yield iterator

by exploiting the idempotence of iter on iterators and doing away with an 
unneeded else -- I also think defaulting arg_cnt to 2 is useful because I see 
myself using this most often for head/tail splits a la ML/Haskell, only 
occasionally for other purposes.  Admittedly, these are minor details.

I'm +0 on the ability to use "head, *tail = rhs" syntax as equivalent to
"head, tail = peel(rhs)".  It's nice and it has an impressionistic analogy
with positional-arguments passing, but not quite the same semantics
as the latter (if tail is to be an iterator rather than a sequence), which
makes it a little bit trickier to teach, and could be seen as a somewhat
gratuitous syntax addition/extension for modest practical gain.  Much
more might be gained by deciding on a small set of iterator-handling
generators to go in a new standard library module -- right now every
substantial user of generators is writing their own little helpers set.  But
maybe waiting until more collective experience on what goes in such
sets is accumulated is wiser.

There are other, less-glamorous situations in which the ability to express 
"whatever number of X's we need here" would help a lot.  For example, the 
struct module lacks the ability to express this reasonably frequent need
(while its Perl counterpart has it), so I find myself using string operations
to construct data-format strings on the fly just for the purpose of ending
them with the appropriate "Nx" or "Ns", or similar workarounds.  Nothing
terrible, but being able to use a 'count' of * for the last element of the
format string would simplify this and make it less error-prone, I think.