diff Python/sysmodule.c @ 15487:f0ca4c67957b legacy-trunk

_getframe(): New sys module function for getting at the stack frame. Implements and closes SF patch #102106, with Guido's suggested documentation changes.
author Barry Warsaw <barry@python.org>
date Wed, 06 Dec 2000 21:47:46 +0000
parents 6f6f965c5e2d
children 0f42f6669e80
line wrap: on
line diff
--- a/Python/sysmodule.c	Wed Dec 06 21:45:33 2000 +0000
+++ b/Python/sysmodule.c	Wed Dec 06 21:47:46 2000 +0000
@@ -15,6 +15,8 @@
 */
 
 #include "Python.h"
+#include "compile.h"
+#include "frameobject.h"
 
 #include "osdefs.h"
 
@@ -284,6 +286,40 @@
 }
 #endif
 
+static char getframe_doc[] =
+"_getframe([depth]) -> frameobject\n\
+\n\
+Return a frame object from the call stack.  If optional integer depth is\n\
+given, return the frame object that many calls below the top of the stack.\n\
+If that is deeper than the call stack, ValueError is raised.  The default\n\
+for depth is zero, returning the frame at the top of the call stack.\n\
+\n\
+This function should be used for internal and specialized\n\
+purposes only.";
+
+static PyObject *
+sys_getframe(PyObject *self, PyObject *args)
+{
+	PyFrameObject *f = PyThreadState_Get()->frame;
+	int depth = -1;
+
+	if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
+		return NULL;
+
+	while (depth > 0 && f != NULL) {
+		f = f->f_back;
+		--depth;
+	}
+	if (f == NULL) {
+		PyErr_SetString(PyExc_ValueError,
+				"call stack is not deep enough");
+		return NULL;
+	}
+	Py_INCREF(f);
+	return (PyObject*)f;
+}
+
+
 #ifdef Py_TRACE_REFS
 /* Defined in objects.c because it uses static globals if that file */
 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
@@ -313,6 +349,7 @@
 	{"getrefcount",	sys_getrefcount, 1, getrefcount_doc},
 	{"getrecursionlimit", sys_getrecursionlimit, 1,
 	 getrecursionlimit_doc},
+	{"_getframe", sys_getframe, 1, getframe_doc},
 #ifdef USE_MALLOPT
 	{"mdebug",	sys_mdebug, 1},
 #endif