简体   繁体   中英

In Python ASTs, when would the targets of an unpacked assignment be a list instead of a tuple?

According to the GreenTreeSnakes documentation on Assignment statements :

An assignment. targets is a list of nodes, and value is a single node.

Multiple nodes in targets represents assigning the same value to each. Unpacking is represented by putting a Tuple or List within targets .

My question is, when does the unpacking put the targets in a List instead of a Tuple? The example given unpacks into a Tuple.

In assignments, targets can both be lists and tuples:

a, b, c = value  # assign to a tuple of names
[a, b, c] = value  # assign to a list of names

The difference is cosmetic to Python; see the Assignment statement reference documentation .

Demo:

>>> parseprint('[a, b, c] = value')
Module(body=[
    Assign(targets=[
        List(elts=[
            Name(id='a', ctx=Store()),
            Name(id='b', ctx=Store()),
            Name(id='c', ctx=Store()),
          ], ctx=Store()),
      ], value=Name(id='value', ctx=Load())),
  ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM