python通过一个PyFrameObject结构体来描述运行时环境
typedef struct _frame {
PyObject_VAR_HEAD
struct _frame *f_back; /* previous frame, or NULL */
PyCodeObject *f_code; /* code segment */
PyObject *f_builtins; /* builtin symbol table (PyDictObject) */
PyObject *f_globals; /* global symbol table (PyDictObject) */
PyObject *f_locals; /* local symbol table (any mapping) */
PyObject **f_valuestack; /* points after the last local */
/* Next free slot in f_valuestack. Frame creation sets to f_valuestack.
Frame evaluation usually NULLs it, but a frame that yields sets it
to the current stack top. */
PyObject **f_stacktop;
PyObject *f_trace; /* Trace function */
/* If an exception is raised in this frame, the next three are used to
* record the exception info (if any) originally in the thread state. See
* comments before set_exc_info() -- it\'s not obvious.
* Invariant: if _type is NULL, then so are _value and _traceback.
* Desired invariant: all three are NULL, or all three are non-NULL. That
* one isn\'t currently true, but "should be".
*/
PyObject *f_exc_type, *f_exc_value, *f_exc_traceback;
PyThreadState *f_tstate;
int f_lasti; /* Last instruction if called */
/* Call PyFrame_GetLineNumber() instead of reading this field
directly. As of 2.3 f_lineno is only valid when tracing is
active (i.e. when f_trace is set). At other times we use
PyCode_Addr2Line to calculate the line from the current
bytecode index. */
int f_lineno; /* Current line number */
int f_iblock; /* index in f_blockstack */
PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */
PyObject *f_localsplus[1]; /* locals+stack, dynamically sized */
} PyFrameObject;
其实一眼就能看出,PyFrameObject中静态的没有什么可以分析的。主要用来存放一些静态的信息,比如说一段CodeObject对应的字节码等等。在python程序运行过程中会不断发生变化的就是最后的f_localsplus[1]这一个值了。这里用到了一个c语言的编程技巧,f_localsplus为一个PyObject的指针数组,大小为1。这样当申请一个大小超过sizeof(PyFrameObject)的结构体对象时,超过的部分就自动分配给f_localsplus。变相的而且更方便的实现动态数组。在为整个运行时环境申请空间时所采用的代码是:
ncells = PyTuple_GET_SIZE(code->co_cellvars); nfrees = PyTuple_GET_SIZE(code->co_freevars); extras = code->co_stacksize + code->co_nlocals + ncells +nfrees; f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras);
于是,整个运行时环境的空间可以被描述为:静态数据的空间+ncell的空间+nfrees的空间+运行时栈的空间+局部变量的空间。在进行逻辑管理的时候主要是下图:
Cell对象和free对象是为了实现闭包
从这一个运行时空间中我们可以看出来,实际上所有的运行时所需操作的对象都是作为局部变量来操作的