planetp
planetp

Reputation: 16065

How does unpacking a nested tuple work in Python?

Trying to assign a value from the datastructure like t = (("foo",),) to a variable, I've found that the following works:

((var,),) = t   # or [[var]] = t

I wonder how it works. Does Python create the tuples/lists on the left side?
A reference to the relevant part in the sources would also be appreciated.

Upvotes: 3

Views: 2864

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121814

Python will unpack values from the right-hand side recursively.

No tuples are created. Instead, the syntax on the left-hand side is interpreted by the compiler to figure out how to assign sequences from the right-hand side.

To see this in action, disassemble assignment code:

>>> def foo():
...     ((var,),) = t
... 
>>> import dis
>>> dis.dis(foo)
  2           0 LOAD_GLOBAL              0 (t)
              3 UNPACK_SEQUENCE          1
              6 UNPACK_SEQUENCE          1
              9 STORE_FAST               0 (var)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE        

Here t is unpacked twice to be stored in var; the compiler determined that the left-hand side is a nested sequence and compiled that down to two UNPACK_SEQUENCE bytecodes.

This is all documented in the assignment statement reference:

Assignment is defined recursively depending on the form of the target (list).

and

Assignment of an object to a target list is recursively defined as follows.

  • If the target list is a single target: The object is assigned to that target.
  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

and

Assignment of an object to a single target is recursively defined as follows.

[...]

  • If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.

That last part particularly tells you that the left-hand side is not interpreted as a Python list or tuple; it just looks the same.

Upvotes: 5

Related Questions