getrecursiondepth

Manlio Perillo NOmanlio_perilloSPAM at libero.it
Sun Sep 26 05:05:03 EDT 2004


On Sun, 26 Sep 2004 00:09:02 GMT, Andrew Dalke <adalke at mindspring.com>
wrote:

>Manlio Perillo wrote:
>>>>>foo()
>> 
>> n = 0 and recursion depth = 1
>> n = 1 and recursion depth = 2
>> n = 2 and recursion depth = 3
>> n = 3 and recursion depth = 4
>
>  Why is it needed?
>

1) To write code that execute once in a function (as C static
variables)
2) To guard against too many recursion


>  Unlike getrecursionlimit it is something that can be
>calculated pretty easily.
>

I think getrecursiondepth is easy to calculate!

>
>Anything which depends on the exact number is going
>to have problems because that depends on the environment.
>For example, in idle getdepth() from its shell
>returns 4 instead of the 2 found in the command-line
>shell.
>
>			

Wait!
I have said that the real getrecursiondepth 'redefines' the origin, so
that outside any function it always returns 0.

Here is the complete source:

--------------------------------------------------
------------ module _pystate.c --------------

#include "Python.h"


static PyObject *
getrecursiondepth(PyObject *self, PyObject *args)
{
	PyThreadState *tstate;

	if (!PyArg_ParseTuple(args, ":recursion_depth"))
		return NULL;

	tstate = PyThreadState_GET();
	return Py_BuildValue("i", tstate->recursion_depth);
}


/* List of functions defined in the module */

static PyMethodDef pystate_methods[] = {
	{"getrecursiondepth", getrecursiondepth, METH_VARARGS,
	  PyDoc_STR("Returns the current recursion level")},
	  {NULL,		NULL}		/* sentinel */
};

PyDoc_STRVAR(module_doc,
"Provides acces to some thread state attributes not present in module
sys");

/* Initialization function for the module */

PyMODINIT_FUNC
init_pystate(void)
{
	Py_InitModule3("_pystate", pystate_methods, module_doc);
}


--------------------------------------------------------------
----------------- module pystate.py -------------------

from _pystate import getrecursiondepth as _getrecursiondepth

_recursion_base = _getrecursiondepth()

def getrecursiondepth():
    return _getrecursiondepth() - _recursion_base

--------------------------------------------------------------



Regards   Manlio Perillo



More information about the Python-list mailing list