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
- Start with Function start calls show
- Do this Inspect the current call stack
- Result start appears as a caller
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.pyIdentify 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.
import traceback
def receipt():
frames = traceback.extract_stack()
print(frames[-2].name)
def checkout():
receipt()
checkout()
checkout
The final frame is receipt itself. The preceding frame names checkout, its direct caller.
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?
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?
What to watch for
A full stack can include local file paths. Choose the fields that belong in a diagnostic log.