最近看到好几篇关于关键字yield的文章,一说与stack pop相近,一说与return相近?Generator? 搞得一团糟糟的…
直接上官网查找下相关资料,搜索结果:
Python yield官方网站搜索
- PEP 342 – Coroutines via Enhanced Generators
- PEP 255 – Simple Generators
- PEP 380 – Syntax for Delegating to a Subgenerator
- PEP 525 – Asynchronous Generators
- PEP 340 – Anonymous Block Statements
- PEP 3152 – Cofunctions
…
这种PEP应该是一种修改草案之类的。文字比较多看的“头疼”。从标题可以看出,关键字眼多为“coroutine" “generator” “cofunction”。说明yield关键字跟generator coroutine cofunction有关。这种比较专业详细。简单点的应该看python官方的reference手册。
6.2.9. Yield expressions
标题中的“expressions"表明yield语句是一个expression–表达式。
yield_atom ::= “(” yield_expression “)”
yield_expression ::= “yield” [expression_list | “from” expression]
这种类型是自然语言描述还是语法树描述?
The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator, and using it in an async def function’s body causes that coroutine function to be an asynchronous generator.
这里大概解释yield的定义–yield是一个关键字。yield语句是一个yield expression–表达式。当用来定义generator function的时,yield表达式只能在一个function函数/方法内部。最后一句:用在async def 函数/方法里会是该函数/方法变成asynchronous状态–也即异步的。
例子:
For example:
def gen(): # defines a generator function
yield 123
async def agen(): # defines an asynchronous generator function
yield 123
Yield expressions are allowed anywhere in a try construct.
Yield表达式可以用在try结构里的任意位置。原文中提到yield定义的function既是generator,就可以通过for、next()和