Explain Codes LogoExplain Codes Logo

Print current call stack from a method in code

python
debugging
logging
pdb
Alex KataevbyAlex Kataev·Dec 20, 2024
TLDR

Unmask your Python code's directional flow using traceback.print_stack(). Incorporate this line of code within any function:

# Who called me? Who, who, who, who? import traceback; traceback.print_stack()

Executing this script pumps out your call sequence, specifying function names and line count, showcasing the procedural path leading to this invocation.

Should you require more control or if stdout is your preferred choice, you can tweak the destination stream:

# strtok_check: Who made the call? import sys, traceback traceback.print_stack(file=sys.stdout)

The "Why, How and What" of call stack introspection

Python gives us more than just a quick peek here. Buckle up as we go on a tour of the debugging Montmartre.

Getting fancy with traceback

If all you need is to capture the stack as a string but not print it, traceback.format_stack() is your knight in shining armor.

# Mystery caller - Who dat, who dat import traceback formatted_stack = traceback.format_stack() print(''.join(formatted_stack))

This could well be your future go-to for logging, and deferred assessments.

pdb, At your service!

For hands-on debugging, set off with Python Debugger (pdb). Summon it using:

# Beam me up, Scotty import pdb; pdb.set_trace()

Once inside the pdb chronicles, use the where command to inspect the call stack. The built-in toolkit not only traces the breadcrumbs but also inspects variables and step-through debugging.

The wise old inspect module

Beyond traceback, the inspect module equips you with the inspect.stack() tool to access the call stack programmatically:

# Dr. Jekyll, meet Mr. Hyde import inspect stack = inspect.stack()

Be it keeping an eye on routine logs or all hands on deck for a complex debugging session, craft a log_stack function to simplify the process.

The do's and don'ts of call stack introspection

The more nifty tools, the greater the responsibility. Here's you guide to the do's and don'ts of call stack introspection.

Debugging made easier

The proverbial needle-in-a-haystack problems are a breeze with call stack at your disposal. With a little effort, function misuse and unexpected execution paths can hardly remain under cover.

Control and flexibility

By directing traceback.print_stack() to streams other than stderr, you get to steer the ship:

# All aboard! Next stop, external file with open('stack_log.txt', 'w') as f: traceback.print_stack(file=f)

Be aware of performance trade-offs

Though indispensable for debugging, take heed of stalling the application or log cluttering while using call stack in high-performance or production environments.