3

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?

Daniel Arteaga
  • 467
  • 3
  • 9

1 Answers1

3

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.

Benoît
  • 16,798
  • 8
  • 46
  • 66
Eirik Fuller
  • 1,454
  • 11
  • 9