[Python-ideas] Fwd: Fwd: unpacking generalisations for list comprehension
Random832
random832 at fastmail.com
Sat Oct 15 04:42:13 EDT 2016
On Sat, Oct 15, 2016, at 04:00, Steven D'Aprano wrote:
> > This is unpacking. It unpacks the results into the destination.
>
> If it were unpacking as it is understood today, with no other changes,
> it would be a no-op. (To be technical, it would convert whatever
> iterable t is into a tuple.)
If that were true, it would be a no-op everywhere.
> I've covered that in an earlier post: if
> you replace *t with the actual items of t, you DON'T get:
Replacing it _with the items_ is not the same thing as replacing it
_with a sequence containing the items_, and you're trying to pull a fast
one by claiming it is by using the fact that the "equivalent loop"
(which is and has always been a mere fiction, not a real transformation
actually performed by the interpreter) happens to use a sequence of
tokens that would cause a tuple to be created if a comma appears in the
relevant position.
> To make this work, the "unpacking operator" needs to do more than just
> unpack. It has to either change append into extend,
Yes, that's what unpacking does. In every context where unpacking means
anything at all, it does something to arrange for the sequence's
elements to be included "unbracketed" in the context it's being
ultimately used in. It's no different from changing BUILD_LIST
(equivalent to creating an empty list and appending each item) to
BUILD_LIST_UNPACK (equivalent to creating an empty list and extending
with each item).
Imagine that we were talking about ordinary list displays, and for some
reason had developed a tradition of explaining them in terms of
"equivalent" code the way we do for comprehensions.
x = [a, b, c] is equivalent to:
x = list()
x.append(a)
x.append(b)
x.append(c)
So now if we replace c with *c [where c == [d, e]], must we now say
this?
x = list()
x.append(a)
x.append(b)
x.append(d, e)
Well, that's just not valid at all. Clearly we must reject this
ridiculous notion of allowing starred expressions within list displays,
because we _can't possibly_ change the transformation to accommodate the
new feature.
More information about the Python-ideas
mailing list