by teddyh · 9y ago · 0 comments
This is normal assignment unpacking:
>>> a, b = 1, 2
>>> [a, b]
[1, 2]
(Mismatch gives errors) >>> a, b = [1]
ValueError
>>> a, b = [1, 2, 3]
ValueError
Extra parentheses works too: >>> (a, b) = [2, 3]
>>> [a, b]
[2, 3]
Unpacking a single value: >>> (a,) = [4]
>>> a
4
Works without parentheses too: >>> a, = [5]
>>> a
5
No values does not work: >>> , = []
SyntaxError
Neither does empty parentheses: >>> () = []
SyntaxError
Now, the oddity: >>> [] = []
>>>
This raises no error! Neither does this: >>> [] = ()
>>>For instance "(a, b)" is "a tuple object containing two things, the values named "a" and "b" so you can still refer to them separately. "[a, b]" is a new list with those same elements, not an alias for "(a, b)".
And there are no collections underneath the LHS, it compiles to an UNPACK_SEQUENCE opcode in both cases:
>>> @dis.dis
... def foo():
... (a, b) = bar()
...
3 0 LOAD_GLOBAL 0 (bar)
3 CALL_FUNCTION 0 (0 positional, 0 keyword pair)
6 UNPACK_SEQUENCE 2
9 STORE_FAST 0 (a)
12 STORE_FAST 1 (b)
15 LOAD_CONST 0 (None)
18 RETURN_VALUE
>>> @dis.dis
... def foo():
... [a, b] = bar()
...
3 0 LOAD_GLOBAL 0 (bar)
3 CALL_FUNCTION 0 (0 positional, 0 keyword pair)
6 UNPACK_SEQUENCE 2
9 STORE_FAST 0 (a)
12 STORE_FAST 1 (b)
15 LOAD_CONST 0 (None)
18 RETURN_VALUE
>>> @dis.dis
... def foo():
... [] = bar()
...
3 0 LOAD_GLOBAL 0 (bar)
3 CALL_FUNCTION 0 (0 positional, 0 keyword pair)
6 UNPACK_SEQUENCE 0
9 LOAD_CONST 0 (None)
12 RETURN_VALUE >>> import dis
>>>
>>> @dis.dis
... def f():
... a, b = 1, 2
... (a, b) = [2, 3]
... (a,) = [4]
... a, = [5]
... [] = []
... [] = ()
...
3 0 LOAD_CONST 6 ((1, 2))
3 UNPACK_SEQUENCE 2
6 STORE_FAST 0 (a)
9 STORE_FAST 1 (b)
4 12 LOAD_CONST 2 (2)
15 LOAD_CONST 3 (3)
18 ROT_TWO
19 STORE_FAST 0 (a)
22 STORE_FAST 1 (b)
5 25 LOAD_CONST 4 (4)
28 STORE_FAST 0 (a)
6 31 LOAD_CONST 5 (5)
34 STORE_FAST 0 (a)
7 37 BUILD_LIST 0
40 UNPACK_SEQUENCE 0
8 43 LOAD_CONST 7 (())
46 UNPACK_SEQUENCE 0
49 LOAD_CONST 0 (None)
52 RETURN_VALUE $ python2
Python 2.7.13 (default, Jul 21 2017, 03:24:34)
>>> () = []
File "<stdin>", line 1
SyntaxError: can't assign to ()
>>>
$ python3
Python 3.6.2 (default, Jul 20 2017, 03:52:27)
>>> () = []
>>>It was fixed in Python 3.6 specifically, the error still occurs under 3.5.