Library contents

Python traceback.extract_stack

Inspect the current call stack to find the caller of a small receipt-formatting function.

A simple example

traceback.extract_stack

  1. Start with Function start calls show
  2. Do this Inspect the current call stack
  3. Result start appears as a caller
The stack records the chain of calls that led to the current line.

Syntax

Python syntax
traceback.extract_stack()
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Identify which step requested a receipt

A document import fails inside a lower-level operation. Preserve enough information to identify the step that requested the document and the original cause when reporting the failure.

Resultcheckout
lesson.py
import traceback

def receipt():
    frames = traceback.extract_stack()
    print(frames[-2].name)

def checkout():
    receipt()

checkout()
Output
checkout

The final frame is receipt itself. The preceding frame names checkout, its direct caller.

Advertisements

Trace an entrance scan

The visitor desk runs its check_in function before reading a badge. At the scan step, inspect the immediately preceding caller frame. Which function asked for the scan?

Givencheck_in → scan
Worked resultcheck_in

Trace a shift scan

The stockroom calls its scanner while handing items to the next worker. At the scan step, inspect the immediately preceding caller frame. Which function asked for the scan?

Givenhandover → scan
Worked resulthandover

What to watch for

A full stack can include local file paths. Choose the fields that belong in a diagnostic log.

Documentation for traceback.extract_stack