gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:17:12 26 4
gpt4 key购买 nike

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 是否实现了这种优化?

最佳答案

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

关于python - CPython 是否实现了 PEP 380 中提到的优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43591542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com