Possibly Pythonic Tail Call Optimization (TCO/TRE)

Terry Reedy tjreedy at udel.edu
Wed Jul 15 02:41:06 CEST 2015

On 7/14/2015 10:02 AM, Antoon Pardon wrote:
> On 07/14/2015 03:43 PM, Chris Angelico wrote:
>> On Tue, Jul 14, 2015 at 11:38 PM, Marko Rauhamaa <marko at pacujo.net> wrote:

>>> No, tail call optimization doesn't change the behavior of the program,
>>> for the worse anyway.
>> It does, because you lose traceback records. That's pretty significant
>> when you come to try to debug something.
> I doubt it would be really significant. Not compared to writing it iteratively.
> When you write it iteratively, you don't get to keep a traceback record per time
> you go throught the loop. So the traceback records you loose in tale call elimination
> would be the traceback records you wouldn't have anyway in the iterative version.

To repeat: loosing tracebacks is probably fine when the function has a 
single *recursive* tail call.  This are precise the cases when it is 
simple and perhaps preferable to use a loop.  But *recursive* tail calls 
are only a small fraction of all tail calls.  So most of the time, the 
loss *would* be significant.  Consider

In moda: def f(a): return modb.g(a-3)

In modb: def g(b): return modc.h(b*(b-1))

In modc: def h(c): return 1.0/c

from moda import f
... (500 lines later)

and your traceback has been reduced to

   In modc: line 1
      return 1.0/c
ZeroDivisionError: ...


Terry Jan Reedy

More information about the Python-list mailing list