Possibly Pythonic Tail Call Optimization (TCO/TRE)

Terry Reedy tjreedy at udel.edu
Thu Jul 16 22:19:37 CEST 2015


On 7/16/2015 7:45 AM, Chris Angelico wrote:
> On Thu, Jul 16, 2015 at 5:31 PM, Antoon Pardon
> <antoon.pardon at rece.vub.ac.be> wrote:


>> 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.

One of the features of Idle is Debug => Stack Viewer, which, when 
invoked immediately after an exception, displays a tree widget with a 
node for each stack frame in the traceback.  Running your code without 
the extra try: except: stuff, so a traceback is displayed, I easily see 
that x is -12, -2, and 0 in f, g, and h.  I suspect that this feature is 
not well known and is underused.

-- 
Terry Jan Reedy



More information about the Python-list mailing list