Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenience function defined for debugging with ipdb in Python

At the top of my Python scripts I have defined the following convenience function for debugging with ipdb:

def bp():
    import ipdb
    ipdb.set_trace()

So when I want to debug in a certain point I can write:

bp() 

instead of having to write

import ipdb; ipdb.set_trace()

(I prefer not to import ipdb unless needed).

The problem with this approach is that when entering pdb I land inside the function bp(), so I have to press 'u' to go to the relevant part of the code:

> /path/to/script.py(15)bp()
      14     import ipdb
 ---> 15     ipdb.set_trace()
      16 

ipdb> u

Is there a way I could have a similar approach, but landing directly into the relevant part of the code?

like image 215
Daniel Arteaga Avatar asked Aug 29 '26 03:08

Daniel Arteaga


1 Answers

One way to change the active frame in a breakpoint defined by a call to ipdb.set_trace() is as follows:

def bp():
    import ipdb
    import sys
    ipdb.set_trace(sys._getframe().f_back)

The same approach does not seem to work for pdb with a simple renaming, but the following seems to work:

def bp():
    from pdb import Pdb
    import sys
    Pdb().set_trace(sys._getframe().f_back)

I tested this in python 3.5, but not in other python versions.

like image 127
Eirik Fuller Avatar answered Aug 30 '26 19:08

Eirik Fuller