Open In App

Traceback in Python

Last Updated : 01 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step. They are usually seen when an exception occurs. Since a traceback gives all the information regarding the exception it becomes easier to track one and fix it.

General structure of a stack trace for an exception:

Traceback for most recent call
Location of the program 
Line in the program where error was encountered
Name of the error: relevant information about the exception 

Example :

Traceback (most recent call last):
  File "C:/Python27/hdg.py", line 5, in 
    value = A[5]
IndexError: list index out of range

The module uses traceback objects, this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().

Functions in the Module

  • traceback.print_tb(tb, limit = None, file = None) : If limit is positive it prints upto limit stack trace entries from traceback object tb. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output.
  • traceback.print_exception(etype, value, tb, limit = None, file = None, chain = True) : Prints exception information and stack trace entries from traceback object tb to file. If tb is not None, it prints a header Traceback (most recent call last): . It prints the exception etype and value after the stack trace. If type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error.
  • traceback.print_exc(limit = None, file = None, chain = True) : This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain).
  • traceback.print_last(limit = None, file = None, chain = True) : It works only after an exception has reached an interactive prompt. This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain).
  • traceback.print_stack(f = None, limit = None, file = None) : If limit is positive, prints up to limit stack trace. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start.
  • traceback.extract_tb(tb, limit = None) : Returns a StackSummary object representing a list of “pre-processed” stack trace entries (FrameSummary object containing attributes filename, lineno, name, and line) extracted from the traceback object tb. It is useful for alternate formatting of stack traces.
  • traceback.extract_stack(f = None, limit = None) : Extracts the raw traceback from the current stack frame. The return value has the same format as for extract_tb().
  • traceback.format_list(extracted_list) : Given a list of tuples or FrameSummary objects returns a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well.
  • traceback.format_exception_only(etype, value) : Formats the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. It returns a list of strings each ending in a new line.
  • traceback.format_exception(etype, value, tb, limit = None, chain = True) : Formats stack trace and exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). It returns a list of strings each ending in new line and some have internal newlines too. When these lines are concatenated and printed they generate an exactly same output as print_exception().
  • traceback.format_exc(limit = None, chain = True) : This is like print_exc(limit) except it returns a string instead of printing to a file.
  • traceback.format_tb(tb, limit = None) : shorthand for format_list(extract_tb(tb, limit)).
  • traceback.format_stack(f = None, limit = None) : shorthand for format_list(extract_stack(f, limit)).
  • traceback.clear_frames(tb) : Clears the local variables of all stack frames in a traceback tb by calling clear() method of each frame object.
  • traceback.walk_stack(f) : Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None, the current stack is used. This helper is used with StackSummary.extract().
  • traceback.walk_tb(tb) : Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract().

Example : Program that prints the exception stack trace.




# importing module
import traceback
  
# declaring array
A = [1, 2, 3, 4]
  
try:
    value = A[5]
      
except:
    # printing stack trace
    traceback.print_exc()
  
# out of try-except
# this statement is to show that the program continues 
# normally after the exception is handled
print("end of program")


Output :

Traceback (most recent call last):
  File "C:/Python27/van.py", line 8, in 
    value = A[5]
IndexError: list index out of range
end of program
>>> 

Classes in the Module

TracebackeException Class : TracebackException objects are created from actual exceptions to capture data for later printing.

class traceback.TracebackException(exc_type, exc_value, exc_traceback, *, limit = None, lookup_lines = True, capture_locals = False)

The class TracebackException contains the following objects:

  • __cause__ : A TracebackException of the original __cause__.
  • __context__ : A TracebackException of the original __context__.
  • __suppress_context__ : The __suppress_context__ value from the original exception.
  • stack : A StackSummary representing the traceback
  • exc_type : The class of the original traceback.
  • filename : For syntax errors – the file name where the error occurred.
  • lineno : For syntax errors – the line number where the error occurred.
  • text : For syntax errors – the text where the error occurred.
  • offset : For syntax errors – the offset into the text where the error occurred.
  • msg : For syntax errors – the compiler error message.
  • classmethod from_exception(exc, *, limit = None, lookup_lines = True, capture_locals = False) : Captures an exception for later rendering.
  • format(*, chain=True) : formats the exception. If chain is not True, __cause__ and __context__ will not be formatted. It returns strings each ending in newline and few have internal newlines as well. The message indicating which exception occurred is always the last string in the output.
  • format_exception_only() : Formats the exception part of the traceback. It also returns strings ending newlines. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output.

Example :




# importing the modules
import traceback
import sys
  
a=3
b=0
try:
    a/b
except Exception as e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    tb = traceback.TracebackException(exc_type, exc_value, exc_tb)
    print(''.join(tb.format_exception_only()))


Output :

ZeroDivisonError: division by zero

StackSummary Class : The objects of this class represent a call stack ready for formatting.

class traceback.StackSummary
  • classmethod extract(frame_gen, *, limit = None, lookup_lines = True, capture_locals = False) : Constructs a StackSummary object from a frame generator.If limit is supplied, only this many frames are taken. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper. If capture_locals is True the local variables in each FrameSummary are captured as object representations.
  • classmethod from_list(a_list) : Constructs a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples.
  • format() : Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well. For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions. In the newer versions however, long sequences of repeated frames are abbreviated.

Example :




# importing the modules
import traceback
import sys
  
def call1(f):
  
  # inside call1()
  # call1() calling call2()
  call2(f)
  
def call2(f):
  # inside call2()
  # calling f()
  f()
  
def f():
    
    # inside f()
    summary = traceback.StackSummary.extract(
        traceback.walk_stack(None)
    )
    print(''.join(summary.format()))
  
# calling f() using call1()
call1(f)


Output :

File "main.py", line 19, in f
    summary = traceback.StackSummary.extract(
  File "main.py", line 14, in call2
    f()
  File "main.py", line 9, in call1
    call2(f)
  File "main.py", line 25, in 
    call1(f)

FrameSummary Class :
FrameSummary objects represent a single frame in a traceback.

class traceback.FrameSummary(filename, lineno, name, lookup_line = True, locals = None, line = None)

It represents a single frame in the traceback or stack that being formatted or printed. It optionally may have stringified versions of the frame in it. If lookup_line is False, the source code is not looked up until the FrameSummary has the line attribute accessed. The line may be directly provided and will prevent line lookups from happening at all. Locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.

Example :




# importing the modules
import traceback
import sys
  
def call1(f):
  
    # inside call1()
    # call1() calling call2()
    call2(f)
  
def call2(f):
    # inside call2()
    # calling f()
    f()
      
template = (
    '{frame.filename}:{frame.lineno}:{frame.name}:\n'
    '    {frame.line}'
)
  
def f():
    summary = traceback.StackSummary.extract(
        traceback.walk_stack(None)
    )
    for frame in summary:
        print(template.format(frame=frame))
  
# calling f() through call1()
call1(f)


Output :

main.py:21:f:
    summary = traceback.StackSummary.extract(
main.py:13:call2:
    f()
main.py:8:call1:
    call2(f)
main.py:28::
    call1(f)

Reference-

  • https://docs.python.org/3/library/traceback.html#traceback.extract_tb
  • https://pymotw.com/3/traceback/


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads