PEP 798 – Unpacking in Comprehensions
9 months ago
- #Python
- #Comprehensions
- #PEP
- PEP 798 proposes extending list, set, and dictionary comprehensions, as well as generator expressions, to allow unpacking notation (* and **) at the start of the expression.
- The proposal aims to provide a concise way of combining an arbitrary number of iterables into one list, set, or generator, or an arbitrary number of dictionaries into one dictionary.
- Motivation includes simplifying common tasks like combining iterables, which currently require explicit loops, double loops in comprehensions, or itertools.chain.
- The proposed syntax is intuitive, as evidenced by students naturally using it in exams, assuming it already existed in Python.
- Specification details include grammar changes to allow starred expressions in comprehensions and generator expressions, with semantics matching existing unpacking behavior.
- Examples show how standard library code could be rewritten more concisely using the new syntax.
- Backwards compatibility is maintained, as currently valid comprehensions remain unaffected.
- Rejected alternatives include further generalizing unpacking operators and handling starred generators as function arguments differently.
- Concerns include potential overuse, ambiguity in function calls, and the impact on external tools.
- Other languages typically use double loops or built-in functions for similar tasks, with few supporting unpacking in comprehensions.