DEV Community

Cover image for Quark's Outlines: Python Traceback Objects
Mike Vincent
Mike Vincent

Posted on

Quark's Outlines: Python Traceback Objects

Quark’s Outlines: Python Traceback Objects

Overview, Historical Timeline, Problems & Solutions

An Overview of Python Traceback Objects

What is a Python traceback object?

When you run a Python program and an error happens, Python shows you a stack trace. A stack trace shows where the error came from. It tells you what function failed and which line caused it. A Python traceback object holds that information.

Each traceback object shows one step in the chain of function calls that led to the error. Python builds this chain as it unwinds the stack. The traceback includes the function’s frame, the line number, and the bytecode instruction that failed.

Python lets you examine what went wrong using traceback objects.

import traceback

try:
    1 / 0
except ZeroDivisionError as e:
    tb = e.__traceback__
    print("Line:", tb.tb_lineno)
Enter fullscreen mode Exit fullscreen mode

This traceback shows the line where the error happened. You can follow it to see how Python reached that point.

What does a Python traceback object contain?

A traceback object stores the frame that was active at the time of the error. It also stores the line number and the last instruction run in that frame. If there were more calls before the error, the traceback links to the next earlier traceback using tb_next.

You can think of a traceback as a trail of breadcrumbs that shows how the program moved from one function to the next before it failed.

Python traceback objects form a chain of frames leading to the error.

def a():
    b()

def b():
    1 / 0

try:
    a()
except ZeroDivisionError as e:
    tb = e.__traceback__
    print("Error in:", tb.tb_frame.f_code.co_name)
Enter fullscreen mode Exit fullscreen mode

This prints the name of the function where the error happened. You can also walk backward using tb_next.


A Historical Timeline of Python Traceback Objects

Where do Python’s traceback objects come from?

Python traceback objects follow the idea of stack traces from earlier programming tools. They allow you to see what went wrong and where. This timeline shows how traceback support in Python grew over time.


People invented ways to trace error locations

1960 —Stack trace messages first appeared in debugging tools for compiled languages.

1970s —Structured error reporting became common in tools for ALGOL and Pascal.


People designed traceback support in Python

1991 —Python added exceptions and built-in stack traces for all uncaught errors.

1994 —Traceback module added to let users walk through exceptions by hand.

2000 —__traceback__ attribute added to exceptions to hold traceback objects.

2010 —Chained exceptions allowed Python to preserve traceback links across raise from.

2020 —Traceback access improved in tools like traceback.TracebackException for structured error analysis.


Problems & Solutions with Python Traceback Objects

How do you use Python traceback objects the right way?

Python traceback objects help you see where an error started, where it happened, and what Python was doing. When an error happens, Python builds a traceback. This traceback helps you trace the flow of execution and fix the problem. Each of these problems shows how to use traceback objects in real code.


Problem: How do you get the line where an error occurred in Python?

You are running some code that raises an error. You want to find the exact line number where the problem happened. You want to get that number from Python, not by reading the stack trace on screen.

Problem: You need to get the line number of the error programmatically.

Solution: Python traceback objects give the line number using tb_lineno.

Python lets you read the error line number from a traceback object.

try:
    int("nope")
except ValueError as e:
    tb = e.__traceback__
    print("Line number:", tb.tb_lineno)
# prints:
# Line number: 2
Enter fullscreen mode Exit fullscreen mode

The tb_lineno attribute gives you the exact line where Python stopped with an error.


Problem: How do you find the function where the error happened in Python?

You are debugging a complex program. You want to know which function caused the error without reading the full traceback printout.

Problem: You want the name of the function where the error occurred.

Solution: Python traceback objects include the frame, which has the code object and its name.

Python lets you get the function name from the traceback’s frame.

def crash():
    return 1 / 0

try:
    crash()
except ZeroDivisionError as e:
    tb = e.__traceback__
    print("Function:", tb.tb_frame.f_code.co_name)
# prints:
# Function: crash
Enter fullscreen mode Exit fullscreen mode

The frame tells you which function was running when the error happened.


Problem: How do you follow all the steps that led to an error in Python?

You are debugging a failure that goes through several functions. You want to walk back through all of them and see which path Python took.

Problem: You need to trace the full call stack leading to an error.

Solution: Python traceback objects form a chain using tb_next.

Python lets you walk the full traceback using tb_next.

def a():
    b()

def b():
    c()

def c():
    1 / 0

try:
    a()
except ZeroDivisionError as e:
    tb = e.__traceback__
    while tb:
        print("Function:", tb.tb_frame.f_code.co_name)
        tb = tb.tb_next
# prints:
# Function: c
# Function: b
# Function: a
Enter fullscreen mode Exit fullscreen mode

You can walk the call chain backwards from the point of error using the tb_next link.


Problem: How do you print a traceback yourself in Python?

You are writing a tool that logs errors to a file. You want to include the full stack trace, not just the error message.

Problem: You want to format and print the traceback manually.

Solution: Python has a traceback module that can format tracebacks from objects.

Python lets you print full tracebacks using the traceback module.

import traceback

try:
    open("/this/does/not/exist.txt")
except Exception as e:
    traceback.print_tb(e.__traceback__)
# prints:
#   File "example.py", line 3, in <module>
#     open("/this/does/not/exist.txt")
Enter fullscreen mode Exit fullscreen mode

This gives you a clean traceback without exiting the program.


Problem: How do you access traceback information from outside an except block in Python?

You are running code in a notebook or tool. You want to access the last traceback after the program stops. You did not save the error at the time.

Problem: You want to read the last exception traceback after the program ends.

Solution: Python keeps the last traceback in sys.last_traceback when run interactively.

Python lets you access the last traceback using the sys module.

import sys

# Only works in interactive mode:
# sys.last_traceback
Enter fullscreen mode Exit fullscreen mode

This lets you recover traceback details even if the program already stopped. It only works if Python is running in interactive mode and the error was uncaught.


Like, Comment, Share, and Subscribe

Did you find this helpful? Let me know by clicking the like button below. I'd love to hear your thoughts in the comments, too! If you want to see more content like this, don't forget to subscribe. Thanks for reading!


Mike Vincent is an American software engineer and app developer from Los Angeles, California. More about Mike Vincent

Top comments (0)