Chapter 6: Function scope

Stack trace

face Josiah Wang

As an aside, the ‘boxes’ are officially called stack frames, because you can imagine stacking a new box on top of the stack of boxes, and then once you remove the top-most box, you will resume execution of your code using the (now) top-most box.

You might actually observe this stack in action when you encounter an error in Python. Try running this code.

1
2
3
4
5
6
7
8
9
def do_bad_math():
    print("Doing bad math")
    i = 0
    return 3 / i

def do_math():
    do_bad_math()

do_math()

Python will give you an error, and also produce a stack trace or stack traceback.

Traceback (most recent call last):
  File "badmath.py", line 9, in <module>
    do_math()
  File "badmath.py", line 7, in do_math
    do_bad_math()
  File "badmath.py", line 4, in do_bad_math
    return 3 / i
ZeroDivisionError: division by zero

Python will return the exact line and function stack that caused the error (line 4 in do_bad_math), and the line in function in the stack before which called it (i.e. line 7 in do_math), and the stack before that (the main program or more precisely line 9 in <module>).