Python assignment destructuring

后端 未结 1 705
夕颜
夕颜 2020-12-30 18:39

These three expressions seem to be equivalent:

a,b,c = line.split()
(a,b,c) = line.split()
[a,b,c] = line.split()

Do they compile to the sa

相关标签:
1条回答
  • 2020-12-30 19:26

    According to dis, they all get compiled to the same bytecode:

    >>> def f1(line):
    ...  a,b,c = line.split()
    ... 
    >>> def f2(line):
    ...  (a,b,c) = line.split()
    ... 
    >>> def f3(line):
    ...  [a,b,c] = line.split()
    ... 
    >>> import dis
    >>> dis.dis(f1)
      2           0 LOAD_FAST                0 (line)
                  3 LOAD_ATTR                0 (split)
                  6 CALL_FUNCTION            0
                  9 UNPACK_SEQUENCE          3
                 12 STORE_FAST               1 (a)
                 15 STORE_FAST               2 (b)
                 18 STORE_FAST               3 (c)
                 21 LOAD_CONST               0 (None)
                 24 RETURN_VALUE        
    >>> dis.dis(f2)
      2           0 LOAD_FAST                0 (line)
                  3 LOAD_ATTR                0 (split)
                  6 CALL_FUNCTION            0
                  9 UNPACK_SEQUENCE          3
                 12 STORE_FAST               1 (a)
                 15 STORE_FAST               2 (b)
                 18 STORE_FAST               3 (c)
                 21 LOAD_CONST               0 (None)
                 24 RETURN_VALUE        
    >>> dis.dis(f3)
      2           0 LOAD_FAST                0 (line)
                  3 LOAD_ATTR                0 (split)
                  6 CALL_FUNCTION            0
                  9 UNPACK_SEQUENCE          3
                 12 STORE_FAST               1 (a)
                 15 STORE_FAST               2 (b)
                 18 STORE_FAST               3 (c)
                 21 LOAD_CONST               0 (None)
                 24 RETURN_VALUE        
    

    So they should all have the same efficiency. As far as which is most Pythonic, it's somewhat down to opinion, but I would favor either the first or (to a lesser degree) the second option. Using the square brackets is confusing because it looks like you're creating a list (though it turns out you're not).

    0 讨论(0)
提交回复
热议问题