Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

syntax - Why can you omit the surrounding parentheses for generators in Python when passing it into a function?

I was just experimenting in Python with different syntax for passing in a generator as an argument to a function, and I realized that although I've been doing this,

>>> sum((j for j in xrange(5)))
10

this works as well:

>>> sum(j for j in xrange(5))
10

This is tested on Python 2.6.6 on Linux. What's going on under the hood? Is it just syntactic sugar? After all, usually an unwrapped generator is indecipherable to the interpreter:

>>> j for j in xrange(5)
  File "<stdin>", line 1
    j for j in xrange(5)
        ^
SyntaxError: invalid syntax
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm sure reading the python grammar will answer that question.

If you prefer plain English over grammars: PEP-289 explains it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...