#Python: Why is this behavior?

5 messages · Page 1 of 1 (latest)

knotty viper
#

I believe for a plain generator expression you need to wrap it in parenthesis?

last yarrow
#

List comprehension need to wrapped in []

cold ingot
#

What do you mean "not really the syntax error"

trail spade
#

Generator expressions don't technically have a bounding token (ie. they don't technically need to be wrapped in parentheses). In practice though the language expects them to be to avoid ambiguity.

for n in items, other_items:
    ...

That's a valid loop that will set n to items then other_items.
Now try to do the same but using a generator expression being passed to a function.

example = func(n for n in items, other_items)

Here you can't tell if the generator is iterating through a tuple of items and other_items or if it's iterating through items while other_items is being passed to func as a second argument.

To prevent this ambiguity it's considered a syntax error if a generator isn't the only thing inside of bounding parentheses. You also can't have a tuple without parentheses as the iterable, that's also a syntax error for the same reason of ambiguity.

#

What I find weird is that this gives a syntax error

example = n for n in items

That doesn't seem ambiguous to me wolfshrug