Skip to main content

Post-mortem debugging tools for Python

Project description

Pymortem: Advanced Python Debugging

PyPI Python Versions License Codecov

Pymortem is a post-mortem debugging tool that lets you inspect and manipulate execution contexts after exceptions occur. Unlike traditional debuggers that require a separate interactive shell, pymortem gives you direct access to all variables and frames in the exception stack, making it valuable in Jupyter notebooks and interactive environments.

This package evolved from an educational blog post on post-mortem debugging techniques. What began as educational code examples has been refined into a practical debugging library.

Installation

pip install pymortem

Features

  • Enhanced Tracebacks: Rich, visual traceback output showing code context around errors with line numbers and error indicators
  • Frame Inspection: Directly examine variables at any level in the call stack without navigating through a separate command interface
  • Code Execution in Context: Run arbitrary code in the context of any stack frame without restarting your program
  • Chained Exception Support: Clear visualization of exception chains, showing both "raised from" and "during handling" relationships
  • No Special Setup: Works with standard Python without requiring breakpoints or special execution modes

Usage

Examining an Exception after it Occurs

# In one cell where an error happens:
def foo():
    x = 10
    output = x / 0
    return output

foo()
# In the next cell, examine the exception:
import pymortem

# Get enhanced traceback and frame information
traceback_msg, frames = pymortem.extract_from_exception()

# Display the improved traceback
print(traceback_msg)

Inspecting Variables in the Error Context

# After running the above cells
# Let's examine the local variables in different frames

# The frame where the error occurred
print("Locals in error frame:", frames[-1]["locals"])

# Check global variables too
print("Some globals:", {k: v for k, v in list(frames[-1]["globals"].items())[:5]})

Executing Code in a Frame's Context

import pymortem
import sys

# Get the most recent exception
exception = pymortem.retrieve_the_last_exception() # Store the exception
_, frames = pymortem.extract_from_exception(exception)

# Choose a frame to work with (e.g., frames[1] for a specific frame)
work_frame = frames[-1]

# Execute code in that frame's context
pymortem.execute(
    """
    # You can access all variables that existed when the error occurred
    print("Available variables:", list(locals().keys()))

    # Test potential fixes without rerunning the entire notebook
    try:
        # Try a fix for a ZeroDivisionError
        denominator = 2  # Was 0 before
        fixed_result = x / denominator
        print(f"Fix worked! Result = {fixed_result}")
    except Exception as e:
        print(f"Fix didn't work: {e}")
    """,
    work_frame
)

Handling Chained Exceptions

# Create a chained exception scenario
try:
    try:
        x = {"key": "value"}
        result = x["missing_key"]  # Will raise KeyError
    except KeyError:
        result = 10 + "0"  # Will raise ValueError
except Exception as e:
    chain_exception = e

# Examine the exception chain
traceback_msg, all_frames = pymortem.extract_from_exception(chain_exception)
print(traceback_msg)
print("")

# Frames are arranged in chronological order, with the first exception first
original_error_frame = all_frames[0]  # Frame from the KeyError
raised_from_frame = all_frames[-1]    # Frame from the ValueError

print(f"First exception type: {type(chain_exception.__cause__)}")
print(f"Second exception type: {type(chain_exception)}")

Why Use Pymortem?

Post-mortem debugging in Python traditionally requires using tools like pdb.pm() or %debug in IPython, which launch a separate command interface with its own syntax and navigation model. Pymortem takes a different approach:

  1. Direct Context Access: Instead of a separate debugging shell, access frame data directly in your current Python environment
  2. Better Visualization: See more context around exceptions with cleaner, more informative tracebacks
  3. Natural Code Execution: Run diagnostic code directly in frame contexts using standard Python syntax
  4. Stays in Flow: Particularly valuable in notebooks where switching to a separate debugging interface breaks your workflow
  5. Handles Complexity: Elegantly deals with nested and chained exceptions that can be confusing in traditional debuggers

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pymortem-1.0.1.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pymortem-1.0.1-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file pymortem-1.0.1.tar.gz.

File metadata

  • Download URL: pymortem-1.0.1.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for pymortem-1.0.1.tar.gz
Algorithm Hash digest
SHA256 957e2a4f3bad0a140dec27f7d6e6ead0c71c19a5b292f0a3e5074bc730dc9b99
MD5 c9d3f501f0a144b6c1f93555eafa58a7
BLAKE2b-256 a3212ed6cd88ac431f2ebfdefda49b2f77bf709137967542718d79eda5d74f16

See more details on using hashes here.

File details

Details for the file pymortem-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: pymortem-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 14.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for pymortem-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f2d2b412d4073de06ec31fa45dfb2ee3b52ed1e3a4c233e8da73eaf314380cb0
MD5 cc2d2e656ff909ea5ce5a5b876d05e8b
BLAKE2b-256 116468fc5395673d6fc71684ae440225894e867f931c05cb0c8179792cc3b783

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page