为什么Python生成器函数与“常规”函数在语法上没有区别?

2024-05-13 03:11:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,在阅读了Improve Your Python: 'yield' and Generators Explained中的生成器,但还没有对它们进行实验,为什么生成函数的语法符号与正则函数的语法符号没有区别。在我的思维实验中,最明显的选择是:

generator generator_name(param):
    # ...
    yield some_other_value

而不是:

^{pr2}$

现在,当人们阅读Python代码时,似乎需要先搜索单词“yield”,然后才能理解某个函数是一个生成器函数。或者,有没有Python约定要求生成器函数有一个指示性名称?像generate_some_value_from_y?在


Tags: and函数yourvalue语法符号somegenerator
1条回答
网友
1楼 · 发布于 2024-05-13 03:11:53

引用PEP 255的话,将生成器引入Python的提议,其中Guido van Rossum(仁慈的生命独裁者,BDFL)解释了为什么没有单独的关键字:

Issue: Introduce another new keyword (say, gen or generator) in place of def, 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. A yield 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.

本质上,生成函数生成生成器,而不是生成器本身。在

相关问题 更多 >