[Python-ideas] Generator unpacking

Sven R. Kunze srkunze at mail.de
Mon Feb 15 10:13:17 EST 2016


On 15.02.2016 15:42, Steven D'Aprano wrote:
> I believe you are misinterpreting the error. The error isn't that you
> are trying to assign to the literal [1,2]. The error is that you are
> trying to assign to the literal 1. It's a subtle difference,

You are indeed right.

And while we are on it, that reminds me of KeyError. I always feel 
annoyed by the fact that Python doesn't tell me what key a dict is missing.

So, if I were to make a suggestion, I would like to see the 
issue-causing thing to be mentioned in those two types of exceptions.

> but
> important to understand that difference in order to understand why [] is
> a legal assignment target.
>
> py> [a, b, c, 1] = "abcd"
>    File "<stdin>", line 1
> SyntaxError: can't assign to literal
>
> Obviously [a, b, c, 1] is not a literal, but 1 is. If there is any
> doubt:
>
> py> [a, b, c, None] = "abcd"
>    File "<stdin>", line 1
> SyntaxError: cannot assign to None
>
>
> Since [1,2] is a *list of assignment targets*, not a single target, the
> assignment you attempted
>
> [1, 2] = [3, 4]
>
> is roughly equivalent to:
>
> 1 = 3
> 2 = 4
>
> which obviously gives a syntax error.
>
> [] is a valid assignment target so long as the right hand side is an
> empty iterable. If it is not empty, you get a TypeError:
>
> py> [] = "abc"
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> ValueError: too many values to unpack
>
>
> There are three values on the right hand side, and zero targets.
>
> This might even be useful. You can confirm that an iterable is empty
> (why you might want to do this, I can't imagine, but suppose you did) by
> assigning it to zero targets:
>
> [] = iterable
>
> succeeds only if iterable has zero items, otherwise it raises
> TypeError.

Completely true and nothing to add; except, as Georg already noted, the 
"as it looks" experience is somewhat weird and I always would consider 
this a syntax error (don't ask me why).


Best,
Sven


More information about the Python-ideas mailing list