Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 6: Function scope
Stack trace
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 |
|
Python will give you an error, and also produce a stack trace or stack traceback.
Traceback (most recent call last):
File "badmath.py", line 8, in <module>
do_math()
File "badmath.py", line 6, in do_math
do_bad_math()
File "badmath.py", line 3, 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 3 in do_bad_math
), and the line in function in the stack before which called it (i.e. line 6 in do_math
), and the stack before that (the main program or more precisely line 8 in <module>
).