current recursion level

Simon Forman rogue_pedro at yahoo.com
Thu Aug 3 23:29:06 EDT 2006


David Bear wrote:
> Is there an easy way to get the current level of recursion? I don't mean
> sys.getrecursionlimit.  I want to know during a live run of a script how
> many times the functions has recursed -- curses, I don't know how to say it
> better.
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --

This might help,

import sys

def getStackDepth():
    '''Return the current call stack depth.'''
    n = 1
    while True:
        try:
            sys._getframe(n)
        except ValueError:
            return n - 1
        n += 1


def f(n=3):
    '''Demo getStackDepth()'''
    print 'hi!', n
    if n:
        return f(n - 1)
    else:
        return getStackDepth()

This is an evil hack. Never use it.

If you really need to know how many times your function has recursed
pass a counter down the "stack" and increment it every time you
recursively call your function.  This will also give you an accurate
count when calling a different function or functions that then
recursively call back into your function, but you'll have to pass your
counter around or *shudder* use a global variable.

def g(n=0):
    '''n is the number of recursions...'''
    if n < 4:
        return g(n + 1)
    else:
        return n


Peace,
~Simon




More information about the Python-list mailing list