0

In the documentation, the definition of the generator expression reads

generator_expression ::=  "(" expression comp_for ")"

whereas in the grammar it is hidden and reads

atom: ('(' [yield_expr|testlist_comp] ')' | .......
testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

According to the grammar, "(" "*" expression comp_for ")" is a valid generator expression but is is not detailed in the documentation. Can someone point me to a concrete example for this kind of generator with a star.

Assuming myList = ((1, 2, 3), (4, 5, 6)), consider for example (*x for x in myList)

  1. myList is an atom
  2. for x in myList matches comp_for according to

    comp_for: 'for' exprlist 'in' or_test

  3. *x matches star_expr thus test|star_expr

  4. *x for x in myList matches testlist_comp
  5. finally (*x for x in myList) is a valid atom because it matches '(' testlist_comp ')'

The python interpreter gives SyntaxError: iterable unpacking cannot be used in comprehension

jlaurens
  • 529
  • 5
  • 10
  • 2
    https://stackoverflow.com/questions/41251729/unpacking-generalizations https://stackoverflow.com/questions/41190547/iterable-unpacking-cannot-be-used-in-comprehension-python-3-operator – Josh Lee Feb 01 '18 at 01:58
  • Do you mean something like `[*x for x in ((1, 2, 3), (4, 5, 6))]`? because i get "SyntaxError: iterable unpacking cannot be used in comprehension" when I try that. Where are you getting that star? – Patrick Haugh Feb 01 '18 at 03:04
  • `(*x,)` works, but has nothing directly to do with your question :) – Mad Physicist Feb 01 '18 at 08:26

1 Answers1

1

What's legal syntax in Python is not exactly the same as what's described by the grammar. The various calls to ast_error in ast.c are examples of cases that are allowed by the grammar but are not valid. "positional argument follows keyword argument" is one of the most familiar: there's nothing in the grammar that disallows

def foo(what=None, how):
    pass

but this does raise a SyntaxError (see this line in ast.c in the cpython source).

Nathan Vērzemnieks
  • 5,495
  • 1
  • 11
  • 23