为什么yield函数在Python中不需要括号?

Why does the yield function not require parentheses in Python?

在Python中,我多次看到用于创建生成器的yield函数。这个函数和print函数在技术上都执行方法的操作,因为它们返回一个值。然而,在从python 2改为python 3的过程中,print函数像普通方法调用一样获得了括号,但yield保持不变。另外,yield获得保留关键字的黄色,而print是保留方法的紫色。为什么yield不被认为是一种方法,并用这种方式着色,而不使用括号语法?

(同样的情况下,为什么return也缺少括号?)

让我再添加一些东西,yield和continue在许多其他语言中也没有括号。我只想知道是什么让它与众不同,除了它是保留的。有许多其他的保留方法可以得到括号。


所以我开始寻找答案。结果是,有一个。从PEP 255,给我们提供yield关键字的PEP

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.


print不是带括号的函数:它从一个语句变成了一个函数。yield仍然是一个声明,就像return一样。语法突出显示是特定于开发环境的。

您可以在这里找到关于表达式和语句之间差异的更多信息,以及关于函数和语句之间差异的更多信息。另请参见有关简单语句和复合语句的文档。


yield不是函数,它是关键字,根据语法,它不需要括号。-

yield_atom ::= "(" yield_expression")"

yield_expression ::="yield" [expression_list]

print曾是python 2中的一条语句,但后来改为python 3中使用pep 3105的内置函数。


print是python 2语言规范定义的关键字,并成为python 3的内置函数(由标准库规范定义)。yield过去是,现在仍然是一个关键字。