Shorter tracebacks

Peter Otten __peter__ at web.de
Sat Dec 13 09:44:45 EST 2008


bearophileHUGS at lycos.com wrote:

> When I write recursive code in Python I sometimes go past the maximum
> allowed stack depth, so I receive a really long traceback. The show of
> such traceback on my screen is very slow (despite a CPU able to
> perform billions of operations each second). So I think I'd like
> something to shorten them.
> I am thinking about something like:
> from __future__ import short_traceback
> 
> That allows me to see only the first and last parts of the stack
> trace, and skips the (generally very redundant) middle part.
> 
> Note that generally using sys.setrecursionlimit(limit) to set a
> smaller limit isn't good, because I may need a big depth anyway.

That's none of __future__'s business, I think. Python offers a hook which
you can modify:

>>> import sys, traceback
>>> from functools import partial
>>> sys.excepthook = partial(traceback.print_exception, limit=5)
>>> x = 0
>>> def f():
...     global x
...     x += 1
...     f()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
  File "<stdin>", line 4, in f
  File "<stdin>", line 4, in f
  File "<stdin>", line 4, in f
RuntimeError: maximum recursion depth exceeded
>>> x
999

Peter



More information about the Python-list mailing list