Debug-friendly stack traces, with variable values and semantic highlighting
Stackprinter is a Python library that provides enhanced, debug-friendly stack traces. It displays more code context, current variable values, and uses semantic highlighting to make tracebacks more readable. The library is actively maintained, with a current version of 0.2.12, and receives updates periodically to support newer Python versions and address issues.
Warnings
- gotcha Python 3.12 users might encounter issues with multi-line f-strings on stackprinter versions older than 0.2.12, as a fix for this was included in version 0.2.12.
- gotcha When handling `ExceptionGroup` objects, older stackprinter versions (prior to 0.2.11) may not fall back gracefully to default tracebacks or might crash. Version 0.2.11 introduced a fix for this.
- gotcha In environments where standard output streams (`sys.stdout`, `sys.stderr`) are unavailable (e.g., `pythonw.exe` GUI applications), stackprinter versions older than 0.2.7 might crash when `show()` is called. Version 0.2.7 introduced graceful degradation.
- gotcha As of version 0.2.4, verbose formatting for `KeyboardInterrupt` exceptions is disabled by default. If you require verbose tracebacks for keyboard interrupts, you must explicitly set `suppressed_exceptions=None` when calling `format()` or `show()`.
- gotcha When inspecting call stacks in multi-threaded programs, variable values displayed by stackprinter represent their state at the time of formatting. These values may have changed in other threads by the time the traceback is printed, potentially leading to misleading information.
Install
-
pip install stackprinter
Imports
- set_excepthook
import stackprinter; stackprinter.set_excepthook()
- show
import stackprinter; stackprinter.show()
- format
import stackprinter; message = stackprinter.format()
- TracePrinter
from stackprinter import TracePrinter
Quickstart
import stackprinter
import logging
import sys
# Option 1: Replace the default excepthook for all uncaught exceptions
# stackprinter.set_excepthook(style='darkbg')
# Option 2: Use in a try-except block or integrate with logging
class VerboseExceptionFormatter(logging.Formatter):
def formatException(self, exc_info):
# exc_info is a tuple (type, value, traceback)
msg = stackprinter.format(exc_info, style='darkbg', source_lines=7, truncate_vals=200)
return msg
def configure_logger(logger_name=None):
formatter = VerboseExceptionFormatter('%(asctime)s %(levelname)s: %(message)s')
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatter)
logger = logging.getLogger(logger_name)
logger.addHandler(handler)
logger.setLevel(logging.ERROR)
return logger
logger = configure_logger('my_app')
def problematic_function(a, b):
result = a / b
return result
def main():
x = 10
y = 0
try:
problematic_function(x, y)
except ZeroDivisionError:
logger.exception('An error occurred during calculation:')
except TypeError as e:
# For manual formatting and printing
print('\n--- Manual stackprinter output ---\n')
stackprinter.show(e, style='darkbg')
if __name__ == '__main__':
main()