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

╄→гoц情女王★ 提交于 2019-11-27 06:56:20

问题


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

回答1:


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

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



来源:https://stackoverflow.com/questions/4799459/why-can-you-omit-the-surrounding-parentheses-for-generators-in-python-when-passi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!