[FIXED] python ipdb.set_trace() one frame "up" (frame=?)

Issue

Sometimes when I invoke ipdb, I know I want to be a frame above where the trace is set. I presume that's why the API exposes the frame parameter (as discussed in href="https://github.com/gotcha/ipdb/blob/master/ipdb/__main__.py" rel="nofollow noreferrer">the documentation).

So here's the function:

import inspect, ipdb

def invoke_a_frame_up():
   ipdb.set_trace(frame=inspect.stack()[i][0])

I'm trying to figure out what i is in the function so that, when invoke_a_frame_up gets called, the trace is not inside invoke_a_frame_up.

Or, more aptly, I'm trying to figure out how to achieve this generally. I've tried every i for the depth of the stack and the trace seems to start at the same frame regardless, until i is greater than the depth, at which point I get IndexError('list index out of range',).


Solution

import inspect
import ipdb

def dbg_up():
    ipdb.set_trace(inspect.currentframe().f_back.f_back)

def foo():
    var = 'in foo'
    bar()

def bar():
    var = 'in bar'
    dbg_up()

foo()

Users of vanilla pdb: your interface is slightly different, like this:

pdb.Pdb().set_trace(inspect.currentframe().f_back.f_back)


Answered By - wim
Answer Checked By - Marilyn (Python.Easybugfix Volunteer)

Related Posts

Post a Comment