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
Traceback (most recent call last): File "C:/Python27/hdg.py", line 5, in value = A 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
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.
Traceback (most recent call last): File "C:/Python27/van.py", line 8, in value = A 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)
TracebackException contains the following objects:
- __cause__ : A
TracebackExceptionof the original
- __context__ : A
TracebackExceptionof the original
- __suppress_context__ : The
__suppress_context__value from the original exception.
- stack : A
StackSummaryrepresenting 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,
__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
SyntaxErrorexceptions, 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.
ZeroDivisonError: division by zero
StackSummary Class : The objects of this class represent a call stack ready for formatting.
- 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.
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.
main.py:21:f: summary = traceback.StackSummary.extract( main.py:13:call2: f() main.py:8:call1: call2(f) main.py:28:: call1(f)
- Python Traceback
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- MySQL-Connector-Python module in Python
- Python - Read blob object in python using wand library
- Python | PRAW - Python Reddit API Wrapper
- twitter-text-python (ttp) module - Python
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Python program to check if the list contains three consecutive common numbers in Python
- Creating and updating PowerPoint Presentations in Python using python - pptx
- How to write an empty function in Python - pass statement?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.