[Python-ideas] Generator unpacking

Sven R. Kunze srkunze at mail.de
Tue Feb 16 05:07:07 EST 2016


On 16.02.2016 00:43, Steven D'Aprano wrote:
> No, it's exactly the same Python idiom (assignment to a list of targets)
> as we've been talking about for the last few posts.

I think we better distinguish between idioms and language features.

> We've had examples
> with four targets, three targets, two targets and zero targets. This is
> an example with one target.
>
> [a] = iterable
>
> requires that the right-hand side be iterable, and after unpacking it
> must contain exactly one item, to match the one assignment target given
> on the left.

Of course, it's quite straightforward once you ponder about it. I 
recently talked to a coworker about this. The concrete example is about 
"How do I get the one-and-only element of a **set** which obviously does 
not support subscripting".


Another aspect, I came to think of is the following asymmetry:

a, b, c, d = mylist4 # works
a, b, c = mylist3    # also works
a, b = mylist2       # works too
[a] = mylist1        # special case?

One might resolve the asymmetry by writing:

[a, b, c, d] = mylist4
[a, b, c] = mylist3
[a, b] = mylist2
[a] = mylist1          # fits in
[] = mylist0           # even that is possible now

Thus, the parentheses-less variants are special cases.

However, when glancing over our production source, the parentheses-less 
variant is rather the norm than a special case (haven't even seen nested 
ones). I suspect a special-character-phobia (ever used a German keyboard 
;-) ?) -- Why should I write '''[a, b] = [b, a]''' when '''a, b = b, 
a''' suffices?

So, it seems to me that inducing the 1-target and 0-target concepts from 
the norm is not that as easy as you might believe.

Last but not least, most devs are not used to magic on the lhs. Imagine 
how weird and interesting you would find that the following being 
possible in Python:

mylist = [6, 7]
a*3, b+5 = mylist


Best,
Sven


More information about the Python-ideas mailing list