Unpacking generalizations

前端 未结 2 1421
暖寄归人
暖寄归人 2020-12-14 06:05

PEP 448 -- Additional Unpacking Generalizations allowed:

>>> LOL = [[1, 2], [\'three\']]
>>> [*LOL[0], *LOL[1]]
[1, 2, \'three\']

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 06:50

    This is briefly explained in the PEP 448 which introduces unpacking generalizations:

    Earlier iterations of this PEP allowed unpacking operators inside list, set, and dictionary comprehensions as a flattening operator over iterables of containers:

    >>> ranges = [range(i) for i in range(5)]
    >>> [*item for item in ranges]
    [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
    
    >>> {*item for item in ranges}
    {0, 1, 2, 3}
    

    This was met with a mix of strong concerns about readability and mild support. In order not to disadvantage the less controversial aspects of the PEP, this was not accepted with the rest of the proposal.

    However, this may change in the future:

    This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals.


    The PEP mentions "strong concerns about readability". I don't know the entire story, but the detailed discussions that led to this decision can certainly be found in the mailing list:

    • [Python-ideas] PEP for issue2292, "Missing *-unpacking generalizations"
    • [Python-ideas] What's going on with PEP 448 - Additional Unpacking Generalizations ?

    Here is an ambiguous example if unpacking generalizations were to be allowed in list comprehension:

    [*t for t in [(1, 'a'), (2, 'b'), (3, 'c')]]
    

    According to one of the core developers, it would be surprising for the result to be [1, 'a', 2, 'b', 3, 'c'] and not [(1, 'a'), (2, 'b'), (3, 'c')].

    Since there was no formal consensus, it was simpler not to allow these special cases.

提交回复
热议问题