Fun with fancy slicing

Alex Martelli aleax at aleax.it
Fri Oct 3 18:51:07 EDT 2003


Fernando Perez wrote:

> Alex Martelli wrote:
> 
>> How sweet it would be to be able to unpack by coding:
>>     head, *tail = alist
> 
> +1000 :)
> 
> I'd LOVE to have this syntax around.  I'd even want:
> 
> head, *body, last = alist
> 
> and
> 
> *head_and_body, last = alist
> 
> to both work in their respectively obvious ways ;) (left-to-right
> unpacking, empty lists/tuples returned for elements which can't be

So far so good...

> unpacked --like if alist contains just one element, and the lhs returning
> tuple/list based on the type of the rhs).

_blink_ uh, what...?

>>> a,b,c='lop'
>>> x=array.array('c','lop')
>>> c,b,a=x
>>> a,b,c=xrange(3)
>>> def tt():
...   yield '1'; yield 22; yield 33
...
>>> a,b,c=tt()

...so WHAT type would you want for the lhs *andalltherest term in each
of these cases...???  I'd be _particularly_ curious about the last one...

In other words, given the rhs in unpacking can be ANY iterable, including,
for example, a generator, it's (IMHO) absurd to try to have the *blah arg
on the lhs 'take on that type'.  Doing it for some special kinds of sequence
and dumping all the others into [e.g.] list or tuple, sort of like filter 
does, is a serious mistake again IMHO -- try teaching *that* a few times.

I would want the type of the rhs to be irrelevant, just as long as it's any
iterable whatsoever, and bundle the 'excess items' into ONE specified
kind of sequence.  I also think it would be best for that one kind to be
tuple, by analogy to argument passing: you can use any iterable as the
actual argument 'expanded' by the *foo form, but whatever type foo
is, if the formal argument is *bar then in the function bar is a TUPLE --
period, simplest, no ifs, no buts.  Maybe using a list instead might have
been better, but tuple was chosen, and I think we should stick to that
for unpacking, because the analogy with argument passing is a good
part of the reason the *foo syntax appeals to me (maybe for the same
reason we should at least for now forego the *foo appearing in any
spot but the last... though that _would_ be a real real pity...).

Oh, and formats for module struct -- THERE, too, allowing a star
would sometimes be very VERY useful and handy, perhaps even
more than in unpacking-assignment...


Alex





More information about the Python-list mailing list