python生成器的源代码在哪里?

2024-04-18 23:50:31 发布

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

问题:

请帮助锁定实现生成器发送部分的Python源代码。我想是在githubThis is Python version 3.8.7rc1的某个地方,但不熟悉存储库的组织方式

背景

在PEP 342和关于发电机发送的文件(值)方面有困难。因此,试图找出它是如何实现的,以理解

  • there is no yield expression to receive a value when the generator has just been created
  • The value argument becomes the result of the **current yield expression**. The send() method returns the **next value yielded by the generator

Specification: Sending Values into Generators

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, and a TypeError is raised if this occurs (presumably due to a logic error of some kind). Thus, before you can communicate with a coroutine you must first call next() or send(None) to advance its execution to the first yield expression.

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

我认为yield就像一个UNIX系统调用进入一个例程,在该例程中保存堆栈帧和执行指针,并挂起生成器协同例程。我认为当调用save(value)时,会出现一些技巧,这些技巧与文档中的神秘部分有关

虽然sent_value = (yield value)是一行语句,但我认为阻塞和恢复都发生在同一行中。执行不会在yield之后恢复,而是在它内部恢复,因此,我想知道block/resume是如何实现的。我也相信next(generator) is the same with generator.send(None)并想核实一下


Tags: ofthetononesendisvaluewith