getrecursiondepth
Manlio Perillo
NOmanlio_perilloSPAM at libero.it
Tue Sep 28 05:59:40 EDT 2004
On Sun, 26 Sep 2004 17:45:38 GMT, Andrew Dalke <adalke at mindspring.com>
wrote:
>Manlio Perillo wrote:
>> 1) To write code that execute once in a function (as C static
>> variables)
>> 2) To guard against too many recursion
>
>Here's a way to get 1). (And I don't know how
>checking the stack depth can be used to emulate
>C's static variable.)
def spam(x):
if getrecursiondepth() == 1:
# initialization code
This is equivalent to C++ code:
struct Init
{
Init() { /* initialization code */ }
};
void spam(int x)
{
static Init init;
...
}
> [...]
>
>In any case, what you're saying is that you
>want to take over control of how to limit
>Python's stack use.
Not really...
>It also means you can't call someone else's
>code because you don't know how that might
>affect the stack.
I don't think that calling someone else's code can affect the current
recursion depth.
>If you don't call someone
>else's code then you can always track your
>stack use yourself by passing a stack depth
>value into your recursion
>
This is simply what I want to do!
>def my_function(x, y, z, max_depth = 20):
> if max_depth == 0: raise RuntimeError( ....)
> ...
> my_function(x-1,y+3,z/2, max_depth-1)
> ...
>
>That is a more common way to solve your problem.
>
I have already used this 'pattern'.
But sometimes I don't want to expose the 'limit' on the argument list.
Actually I have resolved this by doing:
def my_function(x, y, z, __max_depth = 20)
But this means I can't use keyword argument in my function!
>>> Unlike getrecursionlimit it is something that can be
>>>calculated pretty easily.
>>>
>>
>> I think getrecursiondepth is easy to calculate!
>
>True, and I feel somewhat silly in retrospect for
>having said that. For some reason I was thinking
>of a non-recusive way to get that information.
>
>> Wait!
>> I have said that the real getrecursiondepth 'redefines' the origin, so
>> that outside any function it always returns 0.
>
>Ahh, I see your point. But then you don't know
>how much stack space you have available.
This is not a problem!.
getrecursiondepth is not intended for such things.
> [...]
>BTW, I can fool your code
>
>def fool_recusion_base(n=950):
> if n == 0:
> import pystate
> return
> fool_recursion_base(n-1)
>
>fool_recursion_base()
>import pystate
>print pystate.getrecursiondepth()
>
>
Ok, but remember the Python paradigm: we are adult programmers...
>This will probably print a number near -950.
>
>To summarize, I don't see how your solution helps
>you with #1 and think there are better ways to
>handle #2. Could you post code to show how you
>would use your new function?
>
Anyway I have asked why getrecursiondepth is not included in sys
module because many members of the PyThreadState struct are accessible
from Python.
Regards Manlio Perillo
More information about the Python-list
mailing list