How to Print, Read, and Format a Python Traceback

Written by Coursera • Updated on

By the end of this tutorial, you will be able to retrieve, read, print, and format a Python traceback.

[Featured Image] Someone uses a desktop computer to print and log 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.

Glossary

TermDefinition
ExceptionA logical error that occurs during execution.
Printprint() is a function that converts a specified object into text and sends it to the screen or other standard output device.
OutputThe output is the end result of the code you have written. It’s what the computer puts out in response to your commands.
NewlineIn 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.
MethodA 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.

What is a Python traceback?

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: Python Traceback

From bottom to top, here are the elements of the traceback:

  • The red box shows the error type and a description of the exception.
  • The green box shows the line of code that executed when the error occured.
  • The blue box lists the various function calls from most recent to least recent (bottom to top). In this case, you'll see only one call with the line of code indicated.

And here’s an example of a Python traceback in response to a TypeError: type error

Need help?

What if the location the traceback is pointing to doesn’t contain code with an error? Tracebacks aren’t always 100 percent precise. They point to the line where the interpreter first noticed the issue. It can be helpful to note that Python raises an error based on the expression or statement, not the specific argument. The error can come from any part of the expression that’s been thrown.

How to read a Python traceback

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. how to read traceback

Walkthrough: Understanding common Python tracebacks

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: NameError

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:

  1. Delete + drinks
  2. Assign a new list to the variable 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: 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

Learn more about exception types in the previous tutorial: How to Catch, Raise and Print a Python Exception.

Try it yourself

Can you identify and resolve the error being raised in this Python traceback? IndexError

Think about how items are indexed in Python. What would be the correct index for broccoli in the list vegetables?

How to get traceback from an exception in Python

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:

  1. extract_tb(): This function will return a 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:
    • filename
    • lineno
    • name
    • line
  2. extract_stack(): This function extracts the current stack frame’s raw traceback. A stack frame represents just one function call.

How to print traceback in Python

The chart below outlines each print function defined in the Python traceback module:

FunctionMethod
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: Print traceback

How to format a Python traceback

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:

FunctionUse
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().

Key takeaways

  • Python provides a traceback when an exception is raised.
  • You can extract, format, and print stack traces with the Python traceback module.
  • Tracebacks are read from the bottom up. The exception or error encountered is always on the last line of the traceback.
  • Formatting a traceback can provide you with additional information for troubleshooting the error you’ve encountered.

Resources

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.

Continue building your Python expertise with Coursera.

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.


Written by Coursera • Updated on

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.

Learn without limits