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:
- With
ExceptionInfo
andTracebackInfo
, the ability to extract, construct, manipulate, format, and serialize exceptions, tracebacks, and callstacks.- 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.Parameters: - 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()
orfrom_current()
.-
classmethod
from_current
()[source]¶ Create an
ExceptionInfo
object from the current exception being handled, by way ofsys.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 bysys.exc_info()
. See alsofrom_current()
.
-
get_formatted
()[source]¶ 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()
.
-
tb_info_type
¶ Override this in inherited types to control the TracebackInfo type used
alias of
TracebackInfo
-
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. Note
TracebackInfo
can represent both exception tracebacks and non-exception tracebacks (aka stack traces). As a result, there is noTracebackInfo.from_current()
, as that would be ambiguous. Instead, callTracebackInfo.from_frame()
without the frame argument for a stack trace, orTracebackInfo.from_traceback()
without the tb argument for an exception traceback.-
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.Parameters: - frame (types.FrameType) – frame object from
sys._getframe()
or elsewhere. Defaults to result ofsys.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
)
- frame (types.FrameType) – frame object from
-
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
.Parameters: - frame (types.TracebackType) – traceback object from
sys.exc_info()
or elsewhere. If absent or set toNone
, defaults tosys.exc_info()[2]
, and raises aValueError
if no exception is currently being handled. - limit (int) – max number of parent frames to extract
(defaults to
sys.tracebacklimit
)
- frame (types.TracebackType) – traceback object from
-
get_formatted
()[source]¶ 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()
andtraceback.format_stack()
.
-
classmethod
-
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.
Parameters: -
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 thatlineno
andlasti
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).
-
classmethod
-
class
boltons.tbutils.
ContextualExceptionInfo
(exc_type, exc_msg, tb_info)[source]¶ The ContextualTracebackInfo type is a
TracebackInfo
subtype that uses theContextualCallpoint
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.
-
tb_info_type
¶ alias of
ContextualTracebackInfo
-
-
class
boltons.tbutils.
ContextualTracebackInfo
(frames)[source]¶ The ContextualTracebackInfo type is a
TracebackInfo
subtype that is used byContextualExceptionInfo
and uses theContextualCallpoint
as its frame-representing primitive.-
callpoint_type
¶ 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:repr()
outputs for local variables from the Callpoint’s scope- 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()
-
to_dict
()[source]¶ Same principle as
Callpoint.to_dict()
, but with the added contextual values. WithContextualCallpoint.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()
ortraceback.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)
-
source_file
¶ The file path of module containing the function that raised the exception, or None if not available.
-
classmethod