By the end of this tutorial, you will be able to retrieve, read, print, and format a Python traceback.
Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection
Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts
The Python traceback module contains vital information for identifying and resolving problems in your code. Learning to use tracebacks will help you master the Python language and become a stronger programmer overall.
Term | Definition |
---|---|
Exception | A logical error that occurs during execution. |
print() is a function that converts a specified object into text and sends it to the screen or other standard output device. | |
Output | The output is the end result of the code you have written. It’s what the computer puts out in response to your commands. |
Newline | In Python, \n is used to create a new line. If inserted into a string, all characters after \n will be added to a new line. |
Stack trace | A stack trace is a list of method calls that were active at the time that an error or exception was thrown. The term is commonly used synonymously with traceback, although they do notshare the same meaning. A traceback is a module unique to Python. It’s used to format, extract, and print stack traces. |
Method | A method is a function that belongsto an object. For example, a list object has insert, remove, and sort methods associated with it. Methods are called on a specific object. In contrast, functions are called without any object. |
A traceback is a Python module you can use to trace an error back to its source. It reports the function calls made at a specific point in your code. When your code throws (or raises) an exception, Python provides a traceback. Here’s a breakdown of Python traceback structure:
From bottom to top, here are the elements of the traceback:
And here’s an example of a Python traceback in response to a TypeError
:
Need help?
A traceback is full of helpful information, but it can be challenging to digest for the first time. The first rule to remember is that you should read a Python traceback from the bottom up.
In the next section, we’ll dissect a couple of common Python tracebacks to identify their cause, meaning, and how to address them:
NameError
Python raises a NameError
if you’ve referenced a global or local name that hasn’t yet been defined in your code (like a variable, function, or class). Here’s an example:
Reading this from the bottom up, we can see that this block of code caused a NameError
because we didn't define the variable drinks
before attempting to call it in line 4. We could resolve this error in two ways:
+ drinks
drinks
before we define grocery_list
AttributeError
An AttributeError
is raised when a reference or assignment to an attribute has failed. Here’s an example of a Python traceback in response to an AttributeError
:
Starting from the bottom, we can see that we've generated an AttributeError
in line 2 of our code. This was caused by trying to use the attribute append
on the variable drinks
, which we defines as a string. Since string objects have no attribute append
, the interpreter raised an error.
Read more
Can you identify and resolve the error being raised in this Python traceback?
Think about how items are indexed in Python. What would be the correct index for broccoli
in the list vegetables
?
The traceback module provides a standard interface for extracting, printing, and formatting stack traces. If you need to extract a traceback, you have two options in the traceback module:
StackSummary
object. The object represents a list of pre-processed stack trace entries from the traceback object tb. Pre-processed stack trace entries are FrameSummary
objects representing the printed stack trace information. They contain the following attributes:
The chart below outlines each print function defined in the Python traceback module:
Function | Method |
---|---|
traceback.print_tb() | Prints the stack traces from a traceback (tb ) object up to a limit, beginning with the caller’s frame. The limit can be used as a parameter to specify the amount of required trace. In default, the value is None , and Python will print the entire stack trace. |
traceback.print_exception() | Prints exception information and stack trace entries from tb (traceback object) to file. |
traceback.print_exc() | Shorthand for print_exception (*sys.exc_info(), limit, file, chain). Uses sys.exc_info() to get exception information for the current thread, format the results, and print to sys.stderr . |
traceback.print_last() | Shorthand for print_exception (*sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain). An exception must have reached an interactive prompt for this to work. |
traceback.print_stack() | Prints stack trace entries starting from the invocation point up to a limit. All stack trace entries will be printed if the limit is None or omitted. To select an alternate stack frame to start, you can use the fargument. However, it must have the same meaning as for print_tb() . |
Here's an example of how you might print an exception in response to an IndexError
:
The additional information you can uncover by formatting a Python traceback is extremely valuable. You can use it to identify and resolve errors more easily. The following chart defines each formatting function in the Python traceback module:
Function | Use |
---|---|
traceback.format_list() | Return a list of strings ready for print when given a list of tuples or FrameSummary objects as returned by one of the extract functions listed above. |
traceback.format_exception_only() | Format the exception in a traceback by using the exception value. The return value is a list of strings that each end in a newline (\n). By default, the list will contain a single string unless it is for a SyntaxError exception. Those include several lines that display details about where the syntax error occurred upon printing. |
traceback.format_exception() | Format the exception information and a stack trace. Argument meaning is the same as corresponding arguments to print_exception() . The return value is also a list of strings. Each end in a newline. However, some contain internal newlines. |
traceback.format_exc() | Similar to print_exc(limit) . Returns a string rather than printing to a file. |
traceback.format_tb() | Shorthand version of format_list(extract_tb(tb, limit)) . |
traceback.format_stack() | Shorthand version of format_list(extract_stack(f, limit)) . |
traceback.clear_frames() | Calls the clear() method of each frame object, clearing the local variables of all stack frames in a traceback tb. |
traceback.walk_stack() | From the given frame, walk a stack following f.f_back giving the frame and the line number for each frame. If fis None, the current stack will be used. This is employed with StackSummary.extract() |
traceback.walk_tb() | Following tb_next , walk a traceback giving the frame and the line number for each frame. Also employed with StackSummary.extract() . |
You can get involved with the Python community to stay current on tips and recent releases by subscribing to the free Python email newsletter or connecting with peers by joining the Python programming Slack channel.
Take the next step in mastering the Python language by completing a Guided Project like Testing and Debugging Python. For a deeper exploration of the language that rewards your work with a certificate, consider an online course like the Python 3 Programming Specialization from the University of Michigan.
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.