Why does the yield function not require parentheses in Python?
在Python中,我多次看到用于创建生成器的
(同样的情况下,为什么
让我再添加一些东西,yield和continue在许多其他语言中也没有括号。我只想知道是什么让它与众不同,除了它是保留的。有许多其他的保留方法可以得到括号。
所以我开始寻找答案。结果是,有一个。从PEP 255,给我们提供
Q. Why a new keyword for"yield"? Why not a builtin function instead?
A. Control flow is much better expressed via keyword in Python, and
yield is a control construct. It's also believed that efficient
implementation in Jython requires that the compiler be able to
determine potential suspension points at compile-time, and a new
keyword makes that easy. The CPython referrence implementation also
exploits it heavily, to detect which functions are generator-
functions (although a new keyword in place of"def" would solve that
for CPython -- but people asking the"why a new keyword?" question
don't want any new keyword).Q: Then why not some other special syntax without a new keyword? For
example, one of these instead of"yield 3":
1 2 3 4 5 6 7 8 9 10 11 | return 3 and continue return and continue 3 return generating 3 continue return 3 return >> , 3 from generator return 3 return >> 3 return << 3 >> 3 << 3 * 3 |
A: Did I miss one ? Out of hundreds of messages, I counted three
suggesting such an alternative, and extracted the above from them.
It would be nice not to need a new keyword, but nicer to make yield
very clear -- I don't want to have to deduce that a yield is
occurring from making sense of a previously senseless sequence of
keywords or operators. Still, if this attracts enough interest,
proponents should settle on a single consensus suggestion, and Guido
will Pronounce on it.
您可以在这里找到关于表达式和语句之间差异的更多信息,以及关于函数和语句之间差异的更多信息。另请参见有关简单语句和复合语句的文档。
yield_atom ::= "(" yield_expression")"
yield_expression ::="yield" [expression_list]