<commit_before>---
layout: post
title: Python Debugging Trick&#58; pdb.pm()
---

Python's debugger, [pdb](), is a great tool. This post is about one of my favorite uses of pdb, `pdb.pm()`. `pdb.pm()` launches `pdb` to debug the most recently raised exception. When you find yourself saying "Shit! That exception occurred four layers deep in code I wasn't editting and setting up the state to reproduce this is going to take 20 minutes" or "I wish I could just debug right from where the exception was raised", `pdb.pm()` is what you want. 

As a working example, consider the following implementation of mergesort. It has a logic bug, duplicates memory and suffers from array expansion, we will only focus on the logic bug. 

```Python
def mergesort(xs): 
    if len(xs) == 1: 
        return xs 
    else: 
        left = mergesort(xs[:len(xs)//2]) 
        right = mergesort(xs[len(xs)//2:]) 
        ys = [] 
        left_i, right_i = 0, 0 
        while left_i < len(left) or right_i < len(right): 
            if left[left_i] <= right[right_i]: 
                ys.append(left[left_i]) <commit_msg>Complete the link<commit_after>---
layout: post
title: Python Debugging Trick&#58; pdb.pm()
---

Python's debugger, [pdb](https://docs.python.org/3/library/pdb.html), is a great tool. This post is about one of my favorite uses of pdb, `pdb.pm()`. `pdb.pm()` launches `pdb` to debug the most recently raised exception. When you find yourself saying "Shit! That exception occurred four layers deep in code I wasn't editting and setting up the state to reproduce this is going to take 20 minutes" or "I wish I could just debug right from where the exception was raised", `pdb.pm()` is what you want. 

As a working example, consider the following implementation of mergesort. It has a logic bug, duplicates memory and suffers from array expansion, we will only focus on the logic bug. 

```Python
def mergesort(xs): 
    if len(xs) == 1: 
        return xs 
    else: 
        left = mergesort(xs[:len(xs)//2]) 
        right = mergesort(xs[len(xs)//2:]) 
        ys = [] 
        left_i, right_i = 0, 0 
        while left_i < len(left) or right_i < len(right): 
            if left[left_i] <= right[right_i]: 
                ys.append(left[left_i]) 
{'fraction_non_alphanumeric': 0.10612788632326821, 'fraction_numerical': 0.008436944937833037, 'mean_word_length': 3.016042780748663, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4009591', 'n_tokens_mistral': 728, 'n_tokens_neox': 659, 'n_words': 292}