1

I am confused why this code works. In a call to all() I can use syntax which appears like code to generate a list comprehension, but without any parentheses other than the pair for the argument list. Executing the same code outside the argument list results in a syntax error. Calling print on the same code results in the creation of a generator, but without using yield or the (generator comprehension parentheses) ?

Is this special syntax applicable to only function calls, or am I missing something?

all(i for i in range(1, 11)) 
# True

print(i for i in range(1, 11))
# the syntax is creating a generator?
# <generator object <genexpr> at 0x00000000CDD7CC00>

i for i in range(1,11)
#   ^
# SyntaxError: invalid syntax
AndrewL
  • 13
  • 3
  • `all` will take an iterable, and a generator is an iterable. If you want to print it, use arg unpacking like `print(*(i for i in range(1, 11)))` or, more succinctly `print(*range(1,11))` – C.Nivs Aug 23 '19 at 15:19
  • Generator expressions need the `(...)`, but when the expression is the *only argument to a call expression*, you can omit the extra parentheses. – Martijn Pieters Aug 23 '19 at 15:21
  • Also see [Generator expressions](https://docs.python.org/3/reference/expressions.html#generator-expressions) in the documentation. – martineau Aug 23 '19 at 16:18

1 Answers1

2

This is just how the syntax is explicitly defined, see the original PEP:

if a function call has a single positional argument, it can be a generator expression without extra parentheses, but in all other cases you have to parenthesize it.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895