[Python-3000] PEP 3132: Extended Iterable Unpacking
Guido van Rossum
guido at python.org
Mon May 7 19:33:07 CEST 2007
On 5/4/07, Daniel Stutzbach <daniel at stutzbachenterprises.com> wrote:
> On 5/4/07, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> > I don't think that returning the type given is a goal
> > that should be attempted, because it can only ever work
> > for a fixed set of known types. Given an arbitrary
> > sequence type, there is no way of knowing how to
> > create a new instance of it with specified contents.
>
> For objects that support the sequence protocol, how about specifying that:
>
> a, *b = container_object
>
> must be equivalent to:
>
> a, b = container_object[0], container_object[1:]
>
> That way, b is assigned whatever container_object's getslice method
> returns. A list will return a list, a tuple will return a tuple, and
> widgets (or BLists...) can return whatever makes sense for them.
And what do you return when it doesn't support the container protocol?
Think about the use cases. It seems that *your* use case is some kind
of (car, cdr) splitting known from Lisp and from functional languages
(Haskell is built out of this idiom it seems from the examples). But
in Python, if you want to loop over one of those things, you ought to
use a for-loop; and if you really want a car/cdr split, explicitly
using the syntax you show above (x[0], x[1:]) is fine.
The important use case in Python for the proposed semantics is when
you have a variable-length record, the first few items of which are
interesting, and the rest of which is less so, but not unimportant.
(If you wanted to throw the rest away, you'd just write a, b, c =
x[:3] instead of a, b, c, *d = x.) It is much more convenient for this
use case if the type of d is fixed by the operation, so you can count
on its behavior.
There's a bug in the design of filter() in Python 2 (which will be
fixed in 3.0 by turning it into an iterator BTW): if the input is a
tuple, the output is a tuple too, but if the input is a list *or
anything else*, the output is a list. That's a totally insane
signature, since it means that you can't count on the result being a
list, *nor* on it being a tuple -- if you need it to be one or the
other, you have to convert it to one, which is a waste of time and
space. Please let's not repeat this design bug.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000
mailing list