CPython是否实现了PEP 380中提到的优化?

2024-04-18 23:44:28 发布

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

PEP 380提到可以在Python中优化yield from expr语法。你知道吗

PEP 380 - Optimizations

Using a specialised syntax opens up possibilities for optimisation when there is a long chain of generators. Such chains can arise, for instance, when recursively traversing a tree structure. The overhead of passing __next__() calls and yielded values down and up the chain can cause what ought to be an O(n) operation to become, in the worst case, O(n**2).

A possible strategy is to add a slot to generator objects to hold a generator being delegated to. When a __next__() or send() call is made on the generator, this slot is checked first, and if it is nonempty, the generator that it references is resumed instead. If it raises StopIteration, the slot is cleared and the main generator is resumed.

This would reduce the delegation overhead to a chain of C function calls involving no Python code execution. A possible enhancement would be to traverse the whole chain of generators in a loop and directly resume the one at the end, although the handling of StopIteration is more complicated then.

CPython实现了这个优化吗?你知道吗


Tags: andofthetochainforisit
1条回答
网友
1楼 · 发布于 2024-04-18 23:44:28

看起来不像。从python3.6开始,generator object structure没有建议的字段,yield from通过一系列生成器的代码路径总是经历单独恢复其Python堆栈帧的过程。(此代码路径从^{}操作码经过^{}/^{}^{},然后从那里到PyEval_EvalFrameEx再到链中下一个生成器的YIELD_FROM

相关问题 更多 >