Possibly Pythonic Tail Call Optimization (TCO/TRE)

Chris Angelico rosuav at gmail.com
Thu Jul 16 07:45:28 EDT 2015


On Thu, Jul 16, 2015 at 5:31 PM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
> On 07/16/2015 12:43 AM, Gregory Ewing wrote:
>
>> Antoon Pardon wrote:
>>> But it doesn't need to be all or nothing. How about the following possibility.
>>> When the runtime detects a serie of tail calls, it will keep the bottom three
>>> and the top three backtrace records of the serie.
>> Whatever value you choose for N, keeping only the
>> first/last N traceback frames will lead to someone
>> tearing their hair out.
>
> I would say, that someone should get over himself.
> Traceback are not the only or even the most useful
> tool for debugging code. The current stack trace
> doesn't even contain the value's of the variables
> on the stack. So in case of Terry Reedy's example
> that stack trace would IMO have been next to useless.

Actually, they do contain all of that (at least, they do in Py3 - not
sure about Py2 as I haven't checked). You can poke around with the
locals at every point on the stack:

def f(x):
    if x < 10: g(x+10)
    return 5

def g(x):
    if x % 3: h(x + 2)
    return 7

def h(x):
    return 1/x

try:
    x = -12
    print(f(x))
except ZeroDivisionError as e:
    tb = e.__traceback__
    while tb:
        fr = tb.tb_frame
        print("In function %s (%s:%d), x = %r" % (
            fr.f_code.co_name,
            fr.f_code.co_filename,
            fr.f_lineno,
            fr.f_locals["x"],
        ))
        tb = tb.tb_next


It's all there. And it's immensely helpful.

ChrisA



More information about the Python-list mailing list