pythondebuggingpycharmconditional-breakpoint

How to take n steps (iterations) in Python debugger (PyCharm)?


I have a breakpoint in my Python debugger. I am using PyCharm. I want to iterate lets say 100 times to reach the point where I want to debug.

Now I can press 100 x times Resume Program, but is there a way to just execute a command to run n times over the breakpoint.


Solution

  • You can use a function in a conditional breakpoint to count iterations, take for example:

    conditional breakpoint image

    The conditional breakpoint can call a function which in addition to returning a boolean, counts the number of loop iterations.

    def your_counter(stop):
        global count
        count = count + 1
        if stop == count:
            # count = 0 for periodic break
            return True
        else:
            return False
    

    The solution shown is for cases when a one-liner condition might not be practical, and/or when a loop counter needs to be implemented externally. Since the breakpoint condition is programmatic you can implement it to break periodically, or on any series/frequency criteria you want to apply.

    The custom condition would break at the exact iteration you want, after you're done "step debugging" either press resume, stop, "run to cursor", or disable the breakpoint right-clicking on it (in practice this gets you out of the loop).

    You can also change the value of any variable in the middle of debugging by editing in "variable watches".