Friday Finking: initialising values and implied tuples

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Apr 4 20:55:50 EDT 2021


On 5/04/21 11:47 am, dn wrote:
> I think I've read that the compiler is smart-enough to realise that the
> RHS 'literal-tuples'?'tuple-literals' are being used as a 'mechanism',
> and thus the inits are in-lined.

It does indeed seem to do this in some cases:

 >>> def g(i, j, k):
...  a, b, c = i, j, k
...
 >>> dis(g)
   2           0 LOAD_FAST                0 (i)
               2 LOAD_FAST                1 (j)
               4 LOAD_FAST                2 (k)
               6 ROT_THREE
               8 ROT_TWO
              10 STORE_FAST               3 (a)
              12 STORE_FAST               4 (b)
              14 STORE_FAST               5 (c)
              16 LOAD_CONST               0 (None)
              18 RETURN_VALUE

If the RHS is a literal, it's a bit different:

 >>> def f():
...  a, b, c = 1, 2, 3
...
 >>> dis(f)
   2           0 LOAD_CONST               1 ((1, 2, 3))
               2 UNPACK_SEQUENCE          3
               4 STORE_FAST               0 (a)
               6 STORE_FAST               1 (b)
               8 STORE_FAST               2 (c)
              10 LOAD_CONST               0 (None)
              12 RETURN_VALUE

Here the tuple creation is being done at compile time,
so there's still an unpacking operation. It might not be
much different speed-wise from loading the values separately,
though.

-- 
Greg



More information about the Python-list mailing list