Topology of the Python stack

I was composing a comment for a Python try…except statement:

try:
    # …some code
except (KeyboardInterrupt, EOFError):
    print("something")
    # Re-raise the exception for handling “X” in the stack.
    raise

… where “X” could be “lower” or “higher”, depending on your point of view, the system architecture, or the design intent of Python’s creators. So how are execution frames located in relation to each other in the stack, and in relation with the __main__ module? Is there a best, most pythonic terminology?

The __main__ scope is said to be where the “top-level” code executes, but this top-down concept isn’t found anywhere else in the documentation. I searched for variations of the terms “Python stack direction” on search engines and found interesting but ultimately unsatisfying information.

I did find the answer in the Python documentation for the try statement and the execution model.

Actually, the vocabulary used in the Python documentation is intuitive and implementation independent. Inner and outer are the words best used to describe the location of stack frames in relation to one another.

try:
    # …some code
except (KeyboardInterrupt, EOFError):
    print("something")
    # Re-raise the exception for handling outwards in the stack.
    raise

Amended 2015-02-27

I found another reference that uses the top-down topology in the Python debugger module pdb documentation. However, the technical writer must have found “up” and “down” to provide insufficient information so the concept of “newer” and “older” frame was appended in parenthesis.

Debugger Commands (extract)

d(own)
Move the current frame one level down in the stack trace (to a newer frame).
u(p)
Move the current frame one level up in the stack trace (to an older frame).

This reminds me of a familiar sentence! On an exit from an unhandled exception, the stack trace is printed and the first line is:

Traceback (most recent call last):

… and here again is the concept of newer and older frame.

In terms of topology, I guess this would translate as moving “towards the oldest/newest frame in the stack”.

Amended 2015-04-16

Another thing: you raise — rather than drop — an exception, suggesting that older stacks frames are considered to be on top.

Alexandre de Verteuil
Alexandre de Verteuil
Senior Solutions Architect

I teach people how to see the matrix metrics.
Monkeys and sunsets make me happy.

Related