Destination unpacking

Let's say you need to initialize two None variables.
Following Zen of Python , how should I use (and why)?
(provided that the following options are your choice)


Unpack destination

a, b = None, None  # Explicit

or
Appointment

a = b = None # faster. Still readable (perhaps less explicit than unpack?)

The notion of “clearly better” seems to be applicable anyway.

+4
source share
1 answer

Unpacking at assignment with binding

a, b = None, None  # Explicit

The above is explicit. It explicitly and unnecessarily creates an additional data structure:

a, b = None, None   
#makes (None, None) before unpacking and giving to a and b

. , , . :

a = b = None

, , , , , - :

a = None
b = None

, Python 2 3:

import dis

def tupleunpack():
    a, b = None, None

def chainedassignment():
    a = b = None

def multiline():
    a = None
    b = None

>>> dis.dis(tupleunpack)
  2           0 LOAD_CONST               1 ((None, None))
              3 UNPACK_SEQUENCE          2
              6 STORE_FAST               0 (a)
              9 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE
>>> dis.dis(chainedassignment)
  2           0 LOAD_CONST               0 (None)
              3 DUP_TOP
              4 STORE_FAST               0 (a)
              7 STORE_FAST               1 (b)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
>>> dis.dis(multiline)
  2           0 LOAD_CONST               0 (None)
              3 STORE_FAST               0 (a)

  3           6 LOAD_CONST               0 (None)
              9 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE

, . None. .

, Python 3:

, , :

>>> import timeit
>>> timeit.repeat(tupleunpack)
[0.09981771527421301, 0.10060130717376126, 0.10003051661827556]
>>> timeit.repeat(chainedassignment)
[0.09882977371520241, 0.0981032306866183, 0.0982816216005773]
>>> timeit.repeat(multiline)
[0.09878721344639274, 0.09834682031024045, 0.09854603858978805]

Zen, ?

, Zen of Python , Python. , . , , , (, ).

+2

Source: https://habr.com/ru/post/1619100/


All Articles