Python中的堆栈是什么? [英] What is the stack in Python?

查看:124
本文介绍了Python中的堆栈是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中我们怎么称呼堆栈?它是CPython的C堆栈吗?我读到Python堆栈框架是在堆中分配的。但是我认为堆栈的目标是...堆栈堆栈框架。堆栈然后做什么?

What do we call "stack" in Python? Is it the C stack of CPython? I read that Python stackframes are allocated in a heap. But I thought the goal of a stack was... to stack stackframes. What does the stack do then?

推荐答案

略微简化:

在CPython中,当 PyEval_EvalFrameEx 正在评估Python堆栈框架的代码,并进行直接函数调用,它分配一个新的Python堆栈框架,将其链接起来……然后递归调用 PyEval_EvalFrameEx 在新框架上。

In CPython, when PyEval_EvalFrameEx is evaluating a Python stack frame's code, and comes to a direct function call, it allocates a new Python stack frame, links it up… and then recursively calls PyEval_EvalFrameEx on that new frame.

因此, C 堆栈是解释器循环的递归调用堆栈。

So, the C stack is a stack of recursive calls of the interpreter loop.

Python 堆栈是Python框架对象的堆栈,实现为堆已分配对象的简单链接列表。

The Python stack is a stack of Python frame objects, implemented as a simple linked list of heap-allocated objects.

它们并不是完全无关的,但它们不是同一回事。

They're not completely unrelated, but they're not the same thing.

当您使用生成器时,这会变得更加混乱,因为恢复时,可以在不同位置取消链接和重新链接Python堆栈框架。这就是两个堆栈分开的原因。 (请参阅Ned的答案,它比我能更好地解释了这一点。)

When you use generators, this gets slightly more confusing, because those Python stack frames can be unlinked and relinked in different places when they're resumed. Which is why the two stacks are separate. (See Ned's answer, which explains this better than I could.)

这篇关于Python中的堆栈是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆