tbutils - Tracebacks and call stacks

One of the oft-cited tenets of Python is that it is better to ask forgiveness than permission. That is, there are many cases where it is more inclusive and correct to handle exceptions than spend extra lines and execution time checking for conditions. This philosophy makes good exception handling features all the more important. Unfortunately Python’s traceback module is woefully behind the times.

The tbutils module provides two disparate but complementary featuresets:

  1. With ExceptionInfo and TracebackInfo, the ability to extract, construct, manipulate, format, and serialize exceptions, tracebacks, and callstacks.
  2. With ParsedException, the ability to find and parse tracebacks from captured output such as logs and stdout.

There is also the ContextualTracebackInfo variant of TracebackInfo, which includes much more information from each frame of the callstack, including values of locals and neighboring lines of code.

class boltons.tbutils.ExceptionInfo(exc_type, exc_msg, tb_info)[source]

An ExceptionInfo object ties together three main fields suitable for representing an instance of an exception: The exception type name, a string representation of the exception itself (the exception message), and information about the traceback (stored as a TracebackInfo object).

These fields line up with sys.exc_info(), but unlike the values returned by that function, ExceptionInfo does not hold any references to the real exception or traceback. This property makes it suitable for serialization or long-term retention, without worrying about formatting pitfalls, circular references, or leaking memory.

  • exc_type (str) – The exception type name.
  • exc_msg (str) – String representation of the exception value.
  • tb_info (TracebackInfo) – Information about the stack trace of the exception.

Like the TracebackInfo, ExceptionInfo is most commonly instantiated from one of its classmethods: from_exc_info() or from_current().

classmethod from_current()[source]

Create an ExceptionInfo object from the current exception being handled, by way of sys.exc_info(). Will raise an exception if no exception is currently being handled.

classmethod from_exc_info(exc_type, exc_value, traceback)[source]

Create an ExceptionInfo object from the exception’s type, value, and traceback, as returned by sys.exc_info(). See also from_current().


Returns a string formatted in the traditional Python built-in style observable when an exception is not caught. In other words, mimics traceback.format_exception().


alias of TracebackInfo


Get a dict representation of the ExceptionInfo, suitable for JSON serialization.

class boltons.tbutils.TracebackInfo(frames)[source]

The TracebackInfo class provides a basic representation of a stack trace, be it from an exception being handled or just part of normal execution. It is basically a wrapper around a list of Callpoint objects representing frames.

Parameters:frames (list) – A list of frame objects in the stack.


TracebackInfo can represent both exception tracebacks and non-exception tracebacks (aka stack traces). As a result, there is no TracebackInfo.from_current(), as that would be ambiguous. Instead, call TracebackInfo.from_frame() without the frame argument for a stack trace, or TracebackInfo.from_traceback() without the tb argument for an exception traceback.


alias of Callpoint

classmethod from_dict(d)[source]

Complements TracebackInfo.to_dict().

classmethod from_frame(frame=None, level=1, limit=None)[source]

Create a new TracebackInfo frame by recurring up in the stack a max of limit times. If frame is unset, get the frame from sys._getframe() using level.

  • frame (types.FrameType) – frame object from sys._getframe() or elsewhere. Defaults to result of sys.get_frame().
  • level (int) – If frame is unset, the desired frame is this many levels up the stack from the invocation of this method. Default 1 (i.e., caller of this method).
  • limit (int) – max number of parent frames to extract (defaults to sys.tracebacklimit)
classmethod from_traceback(tb=None, limit=None)[source]

Create a new TracebackInfo from the traceback tb by recurring up in the stack a max of limit times. If tb is unset, get the traceback from the currently handled exception. If no exception is being handled, raise a ValueError.

  • frame (types.TracebackType) – traceback object from sys.exc_info() or elsewhere. If absent or set to None, defaults to sys.exc_info()[2], and raises a ValueError if no exception is currently being handled.
  • limit (int) – max number of parent frames to extract (defaults to sys.tracebacklimit)

Returns a string as formatted in the traditional Python built-in style observable when an exception is not caught. In other words, mimics traceback.format_tb() and traceback.format_stack().


Returns a dict with a list of Callpoint frames converted to dicts.

class boltons.tbutils.Callpoint(module_name, module_path, func_name, lineno, lasti, line=None)[source]

The Callpoint is a lightweight object used to represent a single entry in the code of a call stack. It stores the code-related metadata of a given frame. Available attributes are the same as the parameters below.

  • func_name (str) – the function name
  • lineno (int) – the line number
  • module_name (str) – the module name
  • module_path (str) – the filesystem path of the module
  • lasti (int) – the index of bytecode execution
  • line (str) – the single-line code content (if available)
classmethod from_current(level=1)[source]

Creates a Callpoint from the location of the calling function.

classmethod from_frame(frame)[source]

Create a Callpoint object from data extracted from the given frame.

classmethod from_tb(tb)[source]

Create a Callpoint from the traceback of the current exception. Main difference with from_frame() is that lineno and lasti come from the traceback, which is to say the line that failed in the try block, not the line currently being executed (in the except block).


Render the Callpoint as it would appear in a standard printed Python traceback. Returns a string with filename, line number, function name, and the actual code line of the error on up to two lines.


Get a dict copy of the Callpoint. Useful for serialization.

class boltons.tbutils.ContextualExceptionInfo(exc_type, exc_msg, tb_info)[source]

The ContextualTracebackInfo type is a TracebackInfo subtype that uses the ContextualCallpoint as its frame-representing primitive.

It carries with it most of the exception information required to recreate the widely recognizable “500” page for debugging Django applications.


alias of ContextualTracebackInfo

class boltons.tbutils.ContextualTracebackInfo(frames)[source]

The ContextualTracebackInfo type is a TracebackInfo subtype that is used by ContextualExceptionInfo and uses the ContextualCallpoint as its frame-representing primitive.


alias of ContextualCallpoint

class boltons.tbutils.ContextualCallpoint(*a, **kw)[source]

The ContextualCallpoint is a Callpoint subtype with the exact same API and storing two additional values:

  1. repr() outputs for local variables from the Callpoint’s scope
  2. A number of lines before and after the Callpoint’s line of code

The ContextualCallpoint is used by the ContextualTracebackInfo.

classmethod from_frame(frame)[source]

Identical to Callpoint.from_frame()

classmethod from_tb(tb)[source]

Identical to Callpoint.from_tb()


Same principle as Callpoint.to_dict(), but with the added contextual values. With ContextualCallpoint.to_dict(), each frame will now be represented like:

{'func_name': 'print_example',
 'lineno': 0,
 'module_name': 'example_module',
 'module_path': '/home/example/example_module.pyc',
 'lasti': 0,
 'line': 'print "example"',
 'locals': {'variable': '"value"'},
 'pre_lines': ['variable = "value"'],
 'post_lines': []}

The locals dictionary and line lists are copies and can be mutated freely.

boltons.tbutils.print_exception(etype, value, tb, limit=None, file=None)[source]

Print exception up to ‘limit’ stack trace entries from ‘tb’ to ‘file’.

This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header “Traceback (most recent call last):”; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error.

class boltons.tbutils.ParsedException(exc_type_name, exc_msg, frames=None)[source]

Stores a parsed traceback and exception as would be typically output by sys.excepthook() or traceback.print_exception().

classmethod from_string(tb_str)[source]

Parse a traceback and exception from the text tb_str. This text is expected to have been decoded, otherwise it will be interpreted as UTF-8.

This method does not search a larger body of text for tracebacks. If the first line of the text passed does not match one of the known patterns, a ValueError will be raised. This method will ignore trailing text after the end of the first traceback.

Parameters:tb_str (str) – The traceback text (unicode or UTF-8 bytes)

The file path of module containing the function that raised the exception, or None if not available.


Get a copy as a JSON-serializable dict.


Formats the exception and its traceback into the standard format, as returned by the traceback module.

ParsedException.from_string(text).to_string() should yield text.