打电话通用发送()在Python 3.3+中使用新的生成器?

2024-10-01 02:38:56 发布

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

PEP342

Because generator-iterators begin execution at the top of the generator's function body, there is no yield expression to receive a value when the generator has just been created. Therefore, calling send() with a non-None argument is prohibited when the generator iterator has just started, ...

例如

>>> def a():
...     for i in range(5):
...         print((yield i))
... 
>>> g = a()
>>> g.send("Illegal")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't send non-None value to a just-started generator

为什么这是非法的?我在这里理解yield的用法,它暂停函数的执行,并在下次调用next()(或send())时返回到该点。但是打印(yield i)的第一个结果似乎是合法的?你知道吗

以另一种方式问:g = a()后面的生成器“g”处于什么状态。我假设它一直运行a(),直到第一个yield,并且由于有yield,它返回一个生成器,而不是标准的同步对象返回。你知道吗

那么,为什么在新生成器上使用非None参数调用send是非法的呢?

注意:我已经阅读了this question的答案,但并没有真正触及为什么在新生成器上调用send(非None)是非法的。你知道吗


Tags: thetoinnonesendisvaluegenerator
1条回答
网友
1楼 · 发布于 2024-10-01 02:38:56

Asked a different way, in what state is the generator 'g' directly after g = a(). I assumed that it had run a() up until the first yield, and since there was a yield it returned a generator, instead of a standard synchronous object return.

不,就在g = a()之后,就在函数的开头。直到您将生成器提前一次(通过调用next(g)),它才会运行到第一个产量。你知道吗

这是您在问题中引用的内容:“因为生成器迭代器从生成器函数体的顶部开始执行…”它在PEP 255中也这样说,它引入了生成器:

When a generator function is called, the actual arguments are bound to function-local formal argument names in the usual way, but no code in the body of the function is executed.

请注意,yield语句是否实际执行并不重要。仅仅在函数体中出现yield就可以使函数成为生成器,如documented

Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

相关问题 更多 >