Minimising stack trace

Cecil Westerhof Cecil at decebal.nl
Sat May 16 03:22:41 EDT 2015


Op Friday 15 May 2015 21:04 CEST schreef Ned Batchelder:

> On Friday, May 15, 2015 at 2:50:12 PM UTC-4, Cecil Westerhof wrote:
>> While playing with recursion I get:
>> RuntimeError: maximum recursion depth exceeded in comparison
>>
>> But then I get a very long stack trace. Is there a way to make this
>> a lot shorter. Now I 'lose' interesting information because of the
>> length of the stack trace.
>
> There isn't a way to shorten the stack trace.  If you are losing
> information at the top because of your terminal window, you can
> likely increase the number of lines it will keep for you.

Well, I am not really losing information, but it happens in a script
with some output. One of the things I output is information about how
deep I am going. If I then get a stack trace of a 1000 lines that is
not very helpful. Especially because except the first and last every
message is the same. What would be a lot more helpful would be
something like:
    RuntimeError                              Traceback (most recent call last)
    /home/cecil/Python/mathDecebal.py in <module>()
        355         for i in range(start, end + 1):
        356             factorial_iter      = factorial_iterative(i)
    --> 357             factorial_recur     = factorial_recursive(i)
        358             factorial_recur_old = factorial_recursive_old(i)
        359             factorial_tail      = factorial_tail_recursion(i)

    /home/cecil/Python/mathDecebal.py in factorial_recursive(x, y, z)
         51     if x < 2:
         52         return y
    ---> 53     return y if z > x else factorial_recursive(x, z * y, z + 1)
         54 
         55 def factorial_recursive_old(x, y = 1):

    Last call repeated 153 times

    /home/cecil/Python/mathDecebal.py in factorial_recursive(x, y, z)
         48 
         49 def factorial_recursive(x, y = 1, z = 1):
    ---> 50     assert x >= 0
         51     if x < 2:
         52         return y

    RuntimeError: maximum recursion depth exceeded in comparison

I would find that a lot clearer and I do not think you are losing
anything useful.


> Another option is to reduce the maximum stack depth, so that it
> is exceeded sooner, which produces shorter stack traces:
>
> import sys;
> sys.setrecursionlimit(50)

Well that would break my code. I just got the above problem with my
math functions. I had it tweaked for testing. But when running the
test in ipython3 it goes wrong. It looks like ipython3 has a smaller
stack, or puts more on the stack as ipython, python3 and python2.

Yes, that is correct. When running:
    python3 mathDecebal.py
there is no problem, but when running:
    ipython3 mathDecebal.py
I get a stack overflow.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list