sys.setrecursionlimit() and regular expressions

Peter Otten __peter__ at
Thu Sep 30 14:10:38 CEST 2010

Santiago Caracol wrote:

>> Why do you think so? The recursion limit has no effect on the speed of
>> your script. It's just a number that the interpreter checks against.
> Yes, sorry. I was just about to explain that. The 'of course' in my
> post was silly.
> In MY program, the recursion limit is relevant for performance,
> because I use constructs of the following kind:
> def analyze(sentence):
>     try:
>         ...
>     except RuntimeError:
>         ...
> I.e. I try to apply certain recursive rules to a sentence. If this
> doesn't lead to any results (up to recursion limit N),
> then I skip the analysis.

Here's a depth limitation decorator that you can apply selectively. In the 
example below you can have as many gamma() calls as the interpreter's 
recursion limit permits, but only a total of 10 calls of alpha() and beta().

import random

class TooDeep(Exception):

_limit = 10

def limited(f):
    def g(*args, **kw):
        global _limit
        if not _limit:
            raise TooDeep
        _limit -= 1
            return f(*args, **kw)
            _limit += 1
    return g

def alpha(n):
    print "alpha", n

def beta(n):
    print "beta", n

def gamma(n):
    print "gamma", n
    random.choice([alpha, beta, gamma])(n+1)

if __name__ == "__main__":
    except TooDeep as e:
        print e


More information about the Python-list mailing list