[Tutor] Can someone please explain a Stack Trace

Michael P. Reilly arcege@speakeasy.net
Wed, 3 Oct 2001 15:16:04 -0400


On Wed, Oct 03, 2001 at 10:54:36AM -0700, John Day wrote:
> I am trying to learn "verbage" and one item I don't understand fully is
> "Stack Trace".  I have gone through numerous tutorials, yet, it is not
> working for me.  Please help.  Thank You.

This gets into what a "stack" is and how function calls are handled in
basic programming.

A stack is a LIFO (Last-In-First-Out) data structure.  Each item "pushed"
onto a stack is the first item "popped" off; imagine a stack of books,
where you may only remove one from the top.  Each call to a function
is similar: a function is called, and the related data gets pushed onto
a stack.  Each function will have local values and where in the program
the next instruction will be (so when we return from a function we know
were to continue).

When a program fails (not just Python, but other languages as well),
you can get a stack trace, which shows each function that is currently
executing, and where they are in the program.

For example, lets say we have the following program:

def a():
  w2 = "spam"
  return 1/0 # force an exception to be raised

def b(w1):
  print a()

def c(w3=5):
  print b

c()
b("what?")

Now if we execute this, we'll have an exception raised.
$ python /tmp/t1.py
<function b at 80c4250>
Traceback (innermost last):
  File "/tmp/t1.py", line 8, in ?
    b("what?")
  File "/tmp/t1.py", line 6, in b
    print a()
  File "/tmp/t1.py", line 3, in a
    return 1/0 # force an exception to be raised
ZeroDivisionError: integer division or modulo

The trace(-back) shows that first we called "b" with the string "what?"
as the argument.  It was called at line 8 in the main part ("?") of
the file (/tmp/t1.py).  Inside function b, the statement "print a()"
forced a function call to "a", with no arguments at line 6 in the file.
And in a, we ran the statement "return 1/0" which caused the exception.

There is no trace of the function "c" because it already completed,
so its data was "popped" off the stack.

I hope this helps you understand better.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |
| Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html     |