RuntimeError 'maximum recursion depth exceeded'

Gerrit Holl gerrit at nl.linux.org
Sun Nov 16 04:28:21 EST 2003


Georgy Pruss wrote:
> Sometimes I get this error.
> E.g.
> 
> >>> sum = lambda n: n<=1 or n+sum(n-1) # just to illustrate the error
> >>> sum(999)
> 499500
> >>> sum(1000)
> ...........
> RuntimeError: maximum recursion depth exceeded
> 
> Is there any way to set a bigger stack in Python?

Yes, use sys.setrecursionlimit()
See http://www.python.org/dev/doc/devel/lib/module-sys.html :

setrecursionlimit(limit)
    Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

    The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. 

Note that in this case, you can simlpy use the builtin sum:
See http://www.python.org/dev/doc/devel/lib/built-in-funcs.html :

sum(sequence[, start])
    Sums start and the items of a sequence, from left to right, and returns the total. start defaults to 0. The sequence's items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) New in version 2.3. 

...but I assume you already knew the latter, since you said that you example
was just to illustrate the error. Just to be sure.

yours,
Gerrit.

-- 
This space intentionally left blank.
-- 
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Kom in verzet tegen dit kabinet:
	http://www.sp.nl/





More information about the Python-list mailing list