unpacking with default values
Terry Reedy
tjreedy at udel.edu
Thu Jul 17 17:19:08 EDT 2008
McA wrote:
> Do you know the "protocol" used by python while unpacking?
> Is it a direct assingnment? Or iterating?
In CPython, at least, both, just as with normal unpack and multiple
assignment. The iterable is unpacked into pieces by iterating (with
knowledge of the number of targets and which is the catchall). The
targets are then directly bound.
>>> from dis import dis
# first standard assignment
>>> dis(compile("a,b,c = range(3)", '','single'))
1 0 LOAD_NAME 0 (range)
3 LOAD_CONST 0 (3)
6 CALL_FUNCTION 1
9 UNPACK_SEQUENCE 3
12 STORE_NAME 1 (a)
15 STORE_NAME 2 (b)
18 STORE_NAME 3 (c)
21 LOAD_CONST 1 (None)
24 RETURN_VALUE
# now starred assignment
>>> dis(compile("a,b,*c = range(3)", '','single'))
1 0 LOAD_NAME 0 (range)
3 LOAD_CONST 0 (3)
6 CALL_FUNCTION 1
9 UNPACK_EX 2
12 STORE_NAME 1 (a)
15 STORE_NAME 2 (b)
18 STORE_NAME 3 (c)
21 LOAD_CONST 1 (None)
24 RETURN_VALUE
The only difference is UNPACK_EX (tended) instead of UNPACK_SEQUENCE.
Tne UNPACK_EX code is not yet in the dis module documentation.
But a little reverse engineering reveals the parameter meaning:
a,*b,c and *a,b,c give parameters 257 and 512 instead of 2.
Separating 2,257,512 into bytes gives 0,2; 1,1; 2,0.
a,*b and *a,b give 1, 256 or 0,1; 1,0. The two bytes
are the number of targets after and before the starred target.
Terry Jan Reedy
More information about the Python-list
mailing list