我想知道,在阅读了 Improve Your Python: 'yield' and Generators Explained 中关于生成器的内容之后,但还没有对它们进行试验,为什么生成器函数的句法符号与常规函数的句法符号没有区别。在我的思想实验中,最明显的选择是:
generator generator_name(param):
# ...
yield some_other_value
代替:
def generator_name(param):
# ...
yield some_value
现在,当人们阅读 Python 代码时,似乎需要先搜索“yield”一词才能理解某个函数是生成器函数。或者,是否存在要求生成器函数具有指示性名称的 Python 约定?像 generate_some_value_from_y
吗?
最佳答案
引自PEP 255 ,将生成器引入 Python 的提案,其中 Guido van Rossum(Benevolent Dictator for Life,BDFL)解释了为什么没有单独的关键字:
Issue: Introduce another new keyword (say,
gen
orgenerator
) in place ofdef
, or otherwise alter the syntax, to distinguish generator-functions from non-generator functions.Con: In practice (how you think about them), generators are functions, but with the twist that they're resumable. The mechanics of how they're set up is a comparatively minor technical issue, and introducing a new keyword would unhelpfully overemphasize the mechanics of how generators get started (a vital but tiny part of a generator's life).
Pro: In reality (how you think about them), generator-functions are actually factory functions that produce generator-iterators as if by magic. In this respect they're radically different from non-generator functions, acting more like a constructor than a function, so reusing
def
is at best confusing. Ayield
statement buried in the body is not enough warning that the semantics are so different.BDFL:
def
it stays. No argument on either side is totally convincing, so I have consulted my language designer's intuition. It tells me that the syntax proposed in the PEP is exactly right - not too hot, not too cold. But, like the Oracle at Delphi in Greek mythology, it doesn't tell me why, so I don't have a rebuttal for the arguments against the PEP syntax. The best I can come up with (apart from agreeing with the rebuttals ... already made) is "FUD". If this had been part of the language from day one, I very much doubt it would have made Andrew Kuchling's "Python Warts" page.
本质上,生成器函数生成一个生成器,它本身并不是生成器。
关于python - 为什么 Python 生成器函数在语法上与 'regular' 函数没有不同的表示法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182404/