[Python-ideas] Fwd: unpacking generalisations for list comprehension

Nick Coghlan ncoghlan at gmail.com
Fri Oct 14 11:34:18 EDT 2016


On 13 October 2016 at 02:32, Sven R. Kunze <srkunze at mail.de> wrote:
> Here I disagree with you. We use *args all the time, so we know what * does.
> I don't understand why this should not work in between brackets [...].

It does work between brackets:

    >>> [*range(3)]
    [0, 1, 2]

It doesn't work as part of the comprehension syntax, and that's the
case for function calls as well:

    >>> f(*range(i) for i in range(3))
      File "<stdin>", line 1
        f(*range(i) for i in range(3))
                      ^
    SyntaxError: invalid syntax
    >>> [*range(i) for i in range(3)]
      File "<stdin>", line 1
    SyntaxError: iterable unpacking cannot be used in comprehension

(With the less helpful error message in the function call case just
being due to the vagaries of CPython's parser and compiler
implementation, where things that don't even parse are just reported
as "invalid syntax", while problems detected later don't have the
helpful pointer to where in the line parsing failed, but do get a
better explanation of what actually went wrong)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list