pythonrecursiontraceback

Why doesn't the "repeated" number go up in the traceback as I increase the recursion limit?


When I run a recursive function and it exceeds the recursion depth limit, the below error is displayed:

Python 3.12.4+ (heads/3.12:99bc8589f0, Jul 27 2024, 11:20:07) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(): f()
... 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

From what I understand, because the traceback is all the same File "<stdin>", line 1, in f, it does not show it all (because obviously it's not really helpful) and only tells me that this line was repeated 996 times more. When I manually change the recursion limit, I expect that the traceback size grows as well. But it does not:

>>> sys.setrecursionlimit(2000)
>>> 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  [Previous line repeated 997 more times]
RecursionError: maximum recursion depth exceeded

I doubled the recursion limit, so now I expect that traceback size doubles, but it says that the previous line is repeated 997 times. Why is this the case?

Note

I also found this question which seems same as my question, but it isn't. My question is specifically about the size of traceback.

Why does increasing the recursion depth result in stack overflow error?


Solution

  • I figured out that this relates to sys.tracebacklimit variable. It limits the traceback size.

    >>> def f(): f()
    ... 
    >>> 
    >>> import sys
    >>> sys.setrecursionlimit(2000)
    >>> 
    >>> f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in f
      File "<stdin>", line 1, in f
      File "<stdin>", line 1, in f
      [Previous line repeated 997 more times]
    RecursionError: maximum recursion depth exceeded
    >>> 
    >>> sys.tracebacklimit = 1500
    >>> 
    >>> f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in f
      File "<stdin>", line 1, in f
      File "<stdin>", line 1, in f
      [Previous line repeated 1497 more times]
    RecursionError: maximum recursion depth exceeded