How to Use pdb.post_mortem in Python

Automatically enter the Python debugger at the exact point where an uncaught exception occurred, allowing interactive inspection of the crash site.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

16 lines
Python 3.9+
import pdb
import sys

def divide(a, b):
    return a / b

def main():
    try:
        result = divide(10, 0)
        print(f"Result: {result}")
    except Exception:
        # Enter post-mortem debugging when an uncaught exception occurs
        pdb.post_mortem(sys.exc_info()[2])

if __name__ == "__main__":
    main()

Output

stdout
> /path/to/script.py(5)divide()
-> return a / b
(Pdb)

How it works

The try/except block catches the exception, and pdb.post_mortem(sys.exc_info()[2]) passes the traceback object to start debugging at the crash location. You can then inspect variables, evaluate expressions, and step through the code interactively. This technique is invaluable for diagnosing unexpected errors in complex applications without scattering print statements.

Common mistakes

  • Calling pdb.pm() instead of pdb.post_mortem()—both work, but post_mortem is more explicit.
  • Forgetting to pass sys.exc_info()[2]—the traceback object is required.
  • Placing post_mortem outside the except block, causing a NameError.
  • Confusing post_mortem with set_trace()—the latter stops execution at a specific line, not at an exception.

Variations

  1. Use `pdb.pm()` inside the except block for the same behaviour with less boilerplate.
  2. Set the environment variable `PYTHONBREAKPOINT=pdb.post_mortem` to automatically invoke it on any exception.

Real-world use cases

  • Debugging a failed API request in production code to inspect the exact state when an unhandled exception occurs.
  • Investigating a rare crash in a long-running batch job by capturing the post-mortem traceback.
  • Diagnosing a mysterious exception in a data-processing script during development.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.