Assign Many Variables at Once, Python

后端 未结 2 902
慢半拍i
慢半拍i 2021-01-23 08:59

Is there a better way to do this?

a, b, c, = \"yyy\", \"yyy\", \"yyy\"

Obvious attempts fails

a, b, c, = \"yyy\"
a, b, c = \"yy         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-23 09:26

    No need to use tuple assignment here; the right-hand value is immutable, so you can just as well share the reference:

    a = b = c = 'yyy'
    

    This is not unintuitive at all, in my view, and the python compiler will only need to store one constant with the bytecode, while using tuple assignment requires an additional tuple constant:

    >>> def foo():
    ...     a, b, c = 'yyy', 'yyy', 'yyy'
    ... 
    >>> foo.__code__.co_consts
    (None, 'yyy', ('yyy', 'yyy', 'yyy'))
    >>> def bar():
    ...     a = b = c = 'yyy'
    ... 
    >>> bar.__code__.co_consts
    (None, 'yyy')
    

    Don't use this if the right-hand expression is mutable and you want a, b and c to have independent objects; use a generator expression then:

    a, b, c = ({} for _ in range(3))
    

    or better still, don't be so lazy and just type them out:

    a, b, c = {}, {}, {}
    

    It's not as if your left-hand assignment is dynamic.

提交回复
热议问题